Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 534
RiaD Avatar asked Nov 15 '11 16:11

RiaD


2 Answers

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.

like image 52
thiton Avatar answered Sep 28 '22 06:09

thiton


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

like image 23
Steve C Avatar answered Sep 28 '22 07:09

Steve C