禁止使用逗号运算符
我从不使用逗号运算符。
但有时,当我编写一些递归时,我会犯一个愚蠢的错误:我忘记了函数名称。这就是为什么返回最后一个操作数,而不是递归调用的结果。
简单的例子:
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
}
是否有可能得到编译错误而不是不正确的、难以调试的代码?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,但有一个警告。 gcc 有
-Wunused-value
警告(或带有-Werror
的错误)。这将对您的示例生效,因为a*a
无效。编译器结果:但是,这不会捕获单参数调用和所有参数都有副作用的调用(例如
++
)。例如,如果您的最后一行看起来不会触发警告,因为逗号语句的第一部分具有更改
a
的效果。虽然这对于编译器来说是可以诊断的(分配稍后不使用的本地非易失性变量)并且可能会被优化掉,但没有针对它的 gcc 警告。作为参考,手册的完整
-Wunused-value
条目突出显示了 Mike Seymours 的引文:Yes, with a caveat. The gcc has the
-Wunused-value
warning (or error with-Werror
). This will take effect for your example sincea*a
has 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-value
entry of the manual with Mike Seymours quote highlighted:gcc 允许您指定 -Wunused-value ,如果逗号运算符的 LHS 没有副作用,它会向您发出警告。
gcc lets you specify -Wunused-value which will warn you if the LHS of a comma operator has no side effects.