c++

I don't understand the concept of postfix and prefix increment or decrement. Can anyone give a better explanation?


All four answers so far are incorrect , in that they assert a specific order of events.

Believing that "urban legend" has led many a novice (and professional) astray, to wit, the endless stream of questions about Undefined Behavior in expressions.

So.

For the built-in C++ prefix operator,

++x

increments x and produces as expression result x as an lvalue, while

x++

increments x and produces as expression result the original value of x .

In particular, for x++ there is no no time ordering implied for the increment and production of original value of x . The compiler is free to emit machine code that produces the original value of x , eg it might be present in some register, and that delays the increment until the end of the expression (next sequence point).

Folks who incorrectly believe the increment must come first, and they are many, often conclude from that certain expressions must have well defined effect, when they actually have Undefined Behavior.


int i, x;

i = 2;
x = ++i;
// now i = 3, x = 3

i = 2;
x = i++; 
// now i = 3, x = 2

'Post' means after - that is, the increment is done after the variable is read. 'Pre' means before - so the variable value is incremented first, then used in the expression.


No one has answered the question: Why is this concept confusing?

As an undergrad Computer Science major it took me awhile to understand this because of the way I read the code.

The following is not correct!


x = y++

X is equal to y post increment. Which would logically seem to mean X is equal to the value of Y after the increment operation is done. Post meaning after .

or

x = ++y
X is equal to y pre -increment. Which would logically seem to mean X is equal to the value of Y before the increment operation is done. Pre meaning before .


The way it works is actually the opposite. This concept is confusing because the language is misleading. In this case we cannot use the words to define the behavior.
x=++y is actually read as X is equal to the value of Y after the increment.
x=y++ is actually read as X is equal to the value of Y before the increment.

The words pre and post are backwards with respect to semantics of English . They only mean where the ++ is in relation Y. Nothing more.

Personally, if I had the choice I would switch the meanings of ++y and y++. This is just an example of a idiom that I had to learn.

If there is a method to this madness I'd like to know in simple terms.

Thanks for reading.

链接地址: http://www.djcxy.com/p/72250.html

上一篇: 在C ++中,i ++和++ i之间有性能差异吗?

下一篇: C ++