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-valuewarning (or error with-Werror). This will take effect for your example sincea*ahas no effect. Compiler result:However, this won’t catch single-argument calls and calls where all arguments have side effects (like
++). For example, if your last line looked likethe 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-valueentry of the manual with Mike Seymours quote highlighted: