-Wparentheses
is giving me a warning on the following snippet:
-Wparenths向我发出以下代码片段的警告:
long n = -1;
bool asking = true;
do
{
ask_into("Enter the order of this Bezier curve (# of points):", n);
if (asking = n <= 0) // <-- WARNING: "suggest parentheses around assignment used as truth value"
{
std::cout << "Please enter a number > 0.\n";
}
}
while (asking);
The warning goes away if I change the problematic line to this:
如果我将有问题的行更改为以下内容,警告将消失:
if ((asking = n <=0)) // warning gone, but why the double parentheses?
Is there any rationale for the seemingly unnecessary parentheses around the assignment statement or is this just making sure I didn't intend to use ==
instead? Is there a more explicit preferred syntax requiring the parentheses that satisfies this warning without splitting the assignment statement from the conditional?
赋值语句周围看起来不必要的括号有什么道理吗?或者这只是为了确保我不打算使用==?是否有更明确的首选语法需要圆括号来满足此警告,而不将赋值语句与条件语句分开?
If it's any help the compiler I'm using is MSYS2 mingw-w64 g++ 12.2.0
如果有帮助的话,我正在使用的编译器是MSYS2 mingw-W64 g++12.2.0
更多回答
It's making sure you didn't intend to use ==
instead.
这是为了确保您不打算使用==。
The extra parens turns it into an expression. That expression evaluation satisfies the compiler for not being an assignment in the if
expression (because it is an assignment in a sub-expression).
额外的圆括号将其转换为表达式。该表达式计算满足编译器的要求,因为它不是if表达式中的赋值(因为它是子表达式中的赋值)。
@Eljay, it is an expression with or without the extra parentheses. =
is a binary operator. Evaluation of =
expressions produces a value. That's why the extra parentheses are optional, not required.
@eljay,它是一个带或不带额外括号的表达式。=是一个二元运算符。对=表达式求值会产生一个值。这就是为什么额外的圆括号是可选的,而不是必需的。
Same for ==
, by the way.
顺便说一句,==也是一样。
it's close and does tell me how to suppress the warning, but the answer provided by @user17732522 really explains the reasoning for the extra parentheses to suppress the warning, that's what I was curious about, but thank you
它很接近,并且确实告诉我如何取消警告,但@user17732522提供的答案真正解释了为什么要使用额外的括号来取消警告,这就是我好奇的原因,但谢谢你
优秀答案推荐
It is the intended behavior.
这是有意为之的行为。
Part of the -Wparentheses
functionality is to warn if an assignment expression is used as a condition, but only if directly. Extra parentheses around the assignment will make the warning ignore the condition.
-Wparentes功能的一部分是在赋值表达式用作条件时发出警告,但仅当直接使用时才发出警告。赋值前后的额外圆括号将使警告忽略该条件。
The point of it is to make sure that you didn't accidentally write =
instead of ==
, which is a common mistake while ==
is used much more than =
in such a context.
这样做的目的是确保您不会不小心写成=而不是==,这是一个常见的错误,而在这种情况下,==的用法比=多得多。
Because you wouldn't normally add the unnecessary parentheses around the expression, if you did add them, then it is assumed to be a hint that you really thought about it and meant to write it that way, so that a warning shouldn't be produced.
因为您通常不会在表达式周围添加不必要的圆括号,如果您确实添加了它们,那么它被认为是一个提示,表明您确实考虑过它,并打算以这种方式编写它,因此不应该产生警告。
There is no functional difference between having and not having the extra parentheses.
有没有多余的括号在功能上没有区别。
更多回答
我是一名优秀的程序员,十分优秀!