后缀的优先级++
Precedence of postfix ++
考虑这些代码:
int a = 5;
int b = a++;
cout << "b is " << b << endl; // b is 5
或:
int get_number(){
int a = 5;
return a++;
}
int main(){
int b = get_number();
cout << "b is " << b << endl; // b is 5
}
根据 this table 后缀 ++
运算符的优先级高于 =
运算符,因此输出应为 b is 6
。但输出是 b is 5
。我们该如何解释?
内置类型的 postfix++ 运算符(和 postfix-- 运算符)的约定是 returns 以前的值 ,而不管发生。所以函数仍然是 returns 5
,即使收到变化的变量被赋值 6
之后。
根据expr.post.incr,强调我的:
The value of a postfix ++ expression is the value of its operand. [ Note: The value obtained is a copy of the original value — end note ]
The value computation of the ++ expression is sequenced before the
modification of the operand object. With respect to an
indeterminately-sequenced function call, the operation of postfix ++
is a single evaluation
int a = 5;
int b = a++; // the value computation for a is
// the non-modified / non-incremented value
// which is 5
std::cout << "a is " << a << std::endl; // a is 6
std::cout << "b is " << b << std::endl; // b is 5
考虑这些代码:
int a = 5;
int b = a++;
cout << "b is " << b << endl; // b is 5
或:
int get_number(){
int a = 5;
return a++;
}
int main(){
int b = get_number();
cout << "b is " << b << endl; // b is 5
}
根据 this table 后缀 ++
运算符的优先级高于 =
运算符,因此输出应为 b is 6
。但输出是 b is 5
。我们该如何解释?
内置类型的 postfix++ 运算符(和 postfix-- 运算符)的约定是 returns 以前的值 ,而不管发生。所以函数仍然是 returns 5
,即使收到变化的变量被赋值 6
之后。
根据expr.post.incr,强调我的:
The value of a postfix ++ expression is the value of its operand. [ Note: The value obtained is a copy of the original value — end note ]
The value computation of the ++ expression is sequenced before the modification of the operand object. With respect to an indeterminately-sequenced function call, the operation of postfix ++ is a single evaluation
int a = 5;
int b = a++; // the value computation for a is
// the non-modified / non-incremented value
// which is 5
std::cout << "a is " << a << std::endl; // a is 6
std::cout << "b is " << b << std::endl; // b is 5