加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如果条件,检测“=”而不是“==”拼写错误

发布时间:2020-12-16 09:55:15 所属栏目:百科 来源:网络整理
导读:如果我在c中的if条件中使用=而不是==,有没有办法让g产生编译错误?我已经做了几次这个错字,跟踪是很烦人的.那是: if (x=5){ //bad - sets x equal to 5 //do something} 解决方法 -Wparentheses选项专门警告这种情况,这也是-Wall选项的一部分. 从gcc docume
如果我在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 =括号可以转换为错误.

注意

if(x=5) {...}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读