`bool n;` `n++;` 无效但 `n=n+1;` 或 `n=n+3` 这样的东西有效,这有什么意义?
`bool n;` `n++;` is invalid but `n=n+1;` or `n=n+3` such things works what's the significance of this?
代码 C++17
#include <iostream>
int main()
{
bool n=-1;
n++; // Not compiles
n=n+3; // This compiles
return 0;
}
输出
ISO C++17 does not allow incrementing expression of type bool
所以我不明白允许加不可以递增的意义
如您在 standard draft N4296 的第 5.3.2 节中所见,此功能已被弃用
The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated)
请注意,表达式 n=n+3;
不是一元语句,也不是我们可以称之为弃用的东西。如果我们称它为 deprecated,第一个问题是不会有从 bool
到 int
的隐式转换,例如。因为他们不知道你想用非一元语句做什么,所以下面的代码为你提供 i
的输出 2
是合理的(弃用这是不可接受的)
bool b = true;
int i = 1;
i = i + b;
在您的示例中,发生的是 bool->int->bool
的隐式转换
bool n=-1;
n++; // It's a unary statement(so based on the draft, it would not compile)
n=n+3; // This compiles (type(n+3) is now int, and then int is converted to bool)
为什么不推荐使用一元增量?
我使用 Galik 的评论来完成这个答案:
With ++b if you promote the bool b to int you end up with an r-value temporary. You can't increment r-values. So in order for ++b to have ever worked it must have been a bool operation, not a promotion to an arithmetic value. Now, that bool operation has been banned. But promotions remain legal so arithmetic that uses promoted values is fine.
代码 C++17
#include <iostream>
int main()
{
bool n=-1;
n++; // Not compiles
n=n+3; // This compiles
return 0;
}
输出
ISO C++17 does not allow incrementing expression of type bool
所以我不明白允许加不可以递增的意义
如您在 standard draft N4296 的第 5.3.2 节中所见,此功能已被弃用
The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated)
请注意,表达式 n=n+3;
不是一元语句,也不是我们可以称之为弃用的东西。如果我们称它为 deprecated,第一个问题是不会有从 bool
到 int
的隐式转换,例如。因为他们不知道你想用非一元语句做什么,所以下面的代码为你提供 i
的输出 2
是合理的(弃用这是不可接受的)
bool b = true;
int i = 1;
i = i + b;
在您的示例中,发生的是 bool->int->bool
bool n=-1;
n++; // It's a unary statement(so based on the draft, it would not compile)
n=n+3; // This compiles (type(n+3) is now int, and then int is converted to bool)
为什么不推荐使用一元增量?
我使用 Galik 的评论来完成这个答案:
With ++b if you promote the bool b to int you end up with an r-value temporary. You can't increment r-values. So in order for ++b to have ever worked it must have been a bool operation, not a promotion to an arithmetic value. Now, that bool operation has been banned. But promotions remain legal so arithmetic that uses promoted values is fine.