为什么多个增量/减量在C ++中有效,但在C中无效? [英] Why are multiple increments/decrements valid in C++ but not in C?
问题描述
测试.(c/cpp)
#include <stdio.h>
int main(int argc, char** argv)
{
int a = 0, b = 0;
printf("a = %d, b = %d\n", a, b);
b = (++a)--;
printf("a = %d, b = %d\n", a, b);
return 0;
}
如果我将上述内容另存为.cpp文件,它将在执行时编译并输出:
If I save the above as a .cpp file, it compiles and outputs this upon execution:
a = 0, b = 0
a = 0, b = 1
但是,如果将其另存为.c文件,则会出现以下错误:
However, if I save it as a .c file, I get the following error:
test.c:7:12: error: lvalue required as decrement operator.
(++a)
操作是否应该在(newValue)--
操作之前解决?有人对此有见识吗?
Shouldn't the (++a)
operation be resolved before the (newValue)--
operation? Does anyone have any insight on this?
推荐答案
在C中,前缀和后缀递增/递减运算符的结果不是左值.
In C the result of the prefix and postfix increment/decrement operators is not an lvalue.
在C ++中,后缀增减运算符的结果也不是左值,而前缀增减运算符的结果则是左值.
In C++ the result of the postfix increment/decrement operator is also not an lvalue but the result of the prefix increment/decrement operator is an lvalue.
现在在C ++中执行类似(++a)--
的操作是未定义的行为,因为您要在两个序列点之间两次修改对象值.
Now doing something like (++a)--
in C++ is undefined behavior because you are modifying an object value twice between two sequence points.
编辑:关注@ bames53评论.在C ++ 98/C ++ 03中,这是未定义的行为,但是C ++ 11中对序列点概念的更改现在使此表达式得以定义.
following up on @bames53 comment. It is undefined behavior in C++98/C++03 but the changes in C++11 on the idea of sequence points now makes this expression defined.
这篇关于为什么多个增量/减量在C ++中有效,但在C中无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!