Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top