简体   繁体   English

禁止使用逗号运算符

[英]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 ). gcc具有-Wunused-value警告(或带有-Werror错误)。 This will take effect for your example since a*a has no effect. 这将对您的示例生效,因为a*a无效。 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 . 警告不会被触发,因为逗号语句的第一部分具有更改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. 虽然这对于编译器是可诊断的(分配以后未使用的本地非易失性变量)并且可能会被优化掉,但是没有针对它的gcc警告。

For reference, the full -Wunused-value entry of the manual with Mike Seymours quote highlighted: 作为参考,本手册的完整-Wunused-value条目与Mike Seymours引用突出显示:

Warn whenever a statement computes a result that is explicitly not used. 只要语句计算明确未使用的结果,就会发出警告。 To suppress this warning cast the unused expression to void. 要禁止此警告,请将未使用的表达式转换为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. 例如,诸如x [i,j]之类的表达式将导致警告,而x [(void)i,j]则不会。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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