简体   繁体   中英

Disallow using comma operator

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?

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.

gcc允许您指定-Wunused-value ,如果逗号运算符的LHS没有副作用,它将发出警告。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM