Gcc warning: suggest parentheses around assignment used as truth value [-Wparentheses]

/*Snip from gcc manual */

-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.
Also warn if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1
: 0) <= z, which is a different interpretation from that of ordinary mathematical
notation.
Also warn for dangerous uses of the GNU extension to ?: with omitted middle
operand. When the condition in the ?: operator is a boolean expression, the
omitted value is always 1. Often programmers expect it to be a value computed
inside the conditional expression instead.
This warning is enabled by ‘-Wall’.

讲人话,举个例子:

#include <stdio.h>
 
int main(void)
{
    int a = 1;
    int b = 2;
    if (a = b)
    {
        //do nothing
    }
 
    return 0;
}
        在gcc下使用-Wall选项编译,出现告警:

       warning: suggest parentheses around assignment used as truth value [-Wparentheses]

       虽然在判断的语句里使用赋值是很普遍的,例如经典的指针操作语句while(*s++ = *t++)(也会出现告警),但更普遍的现象是人们在使用“=”的时候,明明是想用“==”作比较而非赋值。

       因此,gcc编辑器在-Wall选项下,会明确用户在判断语句中使用“=”的真正意图。有一天,你会庆幸gcc编译器提醒你这个问题。

       当你想在判断语句中使用“=”时,要加上括号:       

if ((a = b) != 0)
          或者

if ((a = b)) (推荐这种方式)
      这样子就可以消除安全隐患,gcc也不会报告警了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值