gpt4 book ai didi

c++ - 在 if 条件下检测 "="而不是 "=="拼写错误

转载 作者:太空狗 更新时间:2023-10-29 20:12:33 25 4
gpt4 key购买 nike

如果我在 C++ 的 if 条件中使用 = 而不是 == ,有没有办法让 g++ 产生编译错误?这个错字我打错了几次,查起来很烦人。即:

if (x=5){ //bad - sets x equal to 5
//do something
}

最佳答案

-Wparentheses 选项专门警告此类情况,这也是 -Wall 选项的一部分。

来自 gcc documentation :

-Wparentheses

Warn if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about.

...

When there is the potential for this confusion, GCC will issue a warning when this flag is specified. To eliminate the warning, add explicit braces around the innermost if statement so there is no way the else could belong to the enclosing if.

可以通过指定 -Werror=parentheses 转换为错误。

注意

if(x=5) {...}

是合法的,标准不需要这样的诊断。但是允许实现提供任意数量的此类有用警告。

关于c++ - 在 if 条件下检测 "="而不是 "=="拼写错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27072251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com