c++11 - C++11 何时给出有关运算符优先级的警告?

标签 c++11 gcc parentheses operator-precedence suppress-warnings

写代码的时候,很长一段时间我都知道&&的优先级比||高;然而,使用 C++11 标准编译它给了我一个警告,现在在单个语句中使用两者时应该使用括号。

现在我收到一条警告,组合>>和+也应该有括号。现在我的语句看起来非常难看,周围有 5 个或更多括号。

1) 是否有资源说明哪些运算符组合现在需要括号?

2)有没有办法只消除运算符优先级警告,但保留其他警告?

带有标志-O2 -Wall -g的编译器gcc

当我添加标志 -std=c++11

时出现警告

示例表达式:

(((string[0] << CHAR_BIT) + string[1] << CHAR_BIT) + string[2] << CHAR_BIT) + string[3];

最佳答案

When does C++11 give warnings about operator precedence?

标准需要诊断消息的唯一情况(请注意,标准不区分警告和停止编译的错误)是程序违反标准的情况。除非编译器被免除,并带有“无需诊断”的措辞。

所有其他警告对于编译器来说都是可选的,而不是标准所要求的。

<小时/>

1) Is there a resource that says which combinations of operators now require parentheses?

否,因为不需要括号。该警告只是编译器的建议。该程序格式良好。

The warnings came in when I added the flag -std=c++11

无论如何,无论标准参数如何,我的 GCC 都会发出警告。

<小时/>

2) Is there a way to silence just the operator precedence warnings, but to keep the other warnings?

警告本身告诉哪个警告选项启用了它(这是来 self 的 GCC 的警告):

warning: suggest parentheses around '+' inside '<<' [-Wparentheses]

要禁用,可以使用相应的选项来禁用它:-Wno-WHATEVER

<小时/>

Now my statements look really ugly, with 5 or more parentheses floating around them.

我建议提取重复结构,并重用标准算法:

std::accumulate(string, string + 4, 0, [](auto sum, auto value) {
    return (sum << CHAR_BIT) + value;
});

括号少得多:) 请注意,在 C++11(C++14 之前的版本)中,您不能使用 auto 作为 lambda 参数的类型。不知道你用的什么类型。

关于c++11 - C++11 何时给出有关运算符优先级的警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44290504/

相关文章:

c++ - typename 给出奇怪的结果 - 在代码块中

c - gcc2.9到5.3不同的汇编指令

linux - 如何使用旧内核为 GNU/Linux 安装构建静态二进制文件?

c++ - 打印第二列时的2d char vector 打印空间

c++ - std::bind 类成员函数

node.js - 如何使 node.js 日志记录格式右括号与左括号相匹配?

powershell - 为什么在这个例子中我们需要括号?

c++ - 将字符串字节与 char C++ 进行比较

c - GNU GCC 数学函数的精度要求?