Disallow using comma operator

…衆ロ難τιáo~ 提交于 2019-12-23 08:00:39

问题


I never use the comma operator.
But sometimes, when I write some recursions, I make a stupid mistake: I forget the function name. That's why the last operand is returned, not the result of a recursion call.

Simplified example:

int binpow(int a,int b){
    if(!b)
        return 1;
    if(b&1)
        return a*binpow(a,b-1);
    return (a*a,b/2); // comma operator
}

Is it possible get a compilation error instead of incorrect, hard to debug code?


回答1:


Yes, with a caveat. The gcc has the -Wunused-value warning (or error with -Werror). This will take effect for your example since a*a has no effect. Compiler result:

test.cpp: In function ‘int binpow(int, int)’:
test.cpp:6:43: warning: left operand of comma operator has no effect [-Wunused-value]

However, this won't catch single-argument calls and calls where all arguments have side effects (like ++). For example, if your last line looked like

return (a *= a, b/2);

the warning would not be triggered, because the first part of the comma statement has the effect of changing a. While this is diagnoseable for a compiler (assignment of a local, non-volatile variable that is not used later) and would probably be optimized away, there is no gcc warning against it.

For reference, the full -Wunused-value entry of the manual with Mike Seymours quote highlighted:

Warn whenever a statement computes a result that is explicitly not used. To suppress this warning cast the unused expression to void. This includes an expression-statement or the left-hand side of a comma expression that contains no side effects. For example, an expression such as x[i,j] will cause a warning, while x[(void)i,j] will not.




回答2:


gcc lets you specify -Wunused-value which will warn you if the LHS of a comma operator has no side effects.



来源:https://stackoverflow.com/questions/8139956/disallow-using-comma-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!