postfix (prefix) increment, L-value and R-value (in C and C++)

不羁岁月 提交于 2019-11-30 21:10:14

C and C++ are different languages. C++ has operator overloading and C does not. The ++ operators, whether prefix or postfix, are operators which can be overloaded in C++. C++ also has references and C does not.

In C, ++i and i++ both yield a value which is not an lvalue. This is desirable, as otherwise you could run afoul with undefined behaviour by trying to modify the same scalar within the same sequence-point boundaries.

Food for thought: In C, the comma operator also produces a value which is not an lvalue, so to "drop" lvalueness, you can do:

(0, lvalue)
Barhom

It is true that

  • pre increment/decrement operator (++var or --var) yields an lvalue (i.e a modifiable object)

  • post increment/decrement operator (var++ or var--) yields an rvalue (i.e a temporary object).

Consider following code with pre increment/decrement operator

{

int i = 0;

int* pi = &(++i);

}

It´s OK because in fact its pseudo code is

i = i+1; // pre increment i

int* pi = &i; // then evaluate its address and assign it to pi 

Now consider the same code but with post increment/decrement operator and its consequences if it was accepted by the compiler

{

int i = 0;

int* pi = &(i++); // Not OK !! because virtually it is a temporary variable

}

Its pseudo code would be

int i = 0;

int tmp = i; // compiler creates a temporary variable to save value of i

int* pi = &tmp; // then would take the address of a temporary variable 

i = i + 1; // the post increment happening only after the assignment !!!

I hope this help clarifying a bit ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!