gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:27:03 24 4
gpt4 key购买 nike

写代码的时候,很长一段时间我都知道&&的优先级比||高;然而,使用 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/

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