禁止使用逗号运算符

发布于 2024-12-15 20:56:27 字数 305 浏览 3 评论 0原文

我从不使用逗号运算符。
但有时,当我编写一些递归时,我会犯一个愚蠢的错误:我忘记了函数名称。这就是为什么返回最后一个操作数,而不是递归调用的结果。

简单的例子:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

影子的影子 2024-12-22 20:56:27

是的,但有一个警告。 gcc 有 -Wunused-value 警告(或带有 -Werror 的错误)。这将对您的示例生效,因为 a*a 无效。编译器结果:

test.cpp: In function ‘int binpow(int, int)’:
test.cpp:6:43: warning: left operand of comma operator has no effect [-Wunused-value]

但是,这不会捕获单参数调用和所有参数都有副作用的调用(例如 ++)。例如,如果您的最后一行看起来

return (a *= a, b/2);

不会触发警告,因为逗号语句的第一部分具有更改 a 的效果。虽然这对于编译器来说是可以诊断的(分配稍后不使用的本地非易失性变量)并且可能会被优化掉,但没有针对它的 gcc 警告。

作为参考,手册的完整 -Wunused-value 条目突出显示了 Mike Seymours 的引文:

每当语句计算出明确未使用的结果时发出警告。要抑制此警告,请将未使用的表达式强制转换为 void。 这包括不包含副作用的表达式语句或逗号表达式的左侧。例如,x[i,j] 等表达式将导致警告,而 x[ (void)i,j] 不会。

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.

护你周全 2024-12-22 20:56:27

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文