/*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也不会报告警了。