开发者

why ++++i regular but i++++ not regular in C++?

When I use i++++ give compile error :

for (int i=1;i<=10;i++++) {} //a.cpp:63: error: lvalue required as increment operand

or

int i = 0;
i++++; // a.cpp:65: error: lvalue required as increment operand

but when I use ++++i is working. Anybody explain me why ++++i regular but i++++ not regular?

开发者_运维技巧

Thanks.


Since type of x is built-in primitive type, both expressions invoke undefined behaviour, as both attempt to modify the same object twice between two sequence points.

Don't do either of them.

Read this FAQ :

Undefined behavior and sequence points


However if the type of x is a user-defined type and you've overloaded operator++ for both expressions, then both would be well-defined.

For this, see this topic to know the explanation and details:

Undefined behavior and sequence points reloaded


The C++ standard says in section 5.2.6 that the result of i++ is a modifiable lvalue, and in 5.3.2 that the result of ++i is a modifiable lvalue. This can help explain why i++++ and ++++i aren't required to generate diagnostics and can appear to work sometimes.

However, ++++i modifies i twice between the previous and next sequence points, so the result is still going to be undefined behaviour. ++++i is allowed to work but it doesn't have to.

Luckily for you, your compiler diagnosed i++++.


Because the operators' conceptual "signatures" are:

​T& operator ++(T& a);​     // pre
​T operator ++(T& a, int);​ // post
                          // note the int is solely to distinguish the two

One returns a reference (an lvalue), and the other does not. Both, however, take a reference as their argument, so the one that returns a reference (++i) can be chained, and the one that does not (i++) cannot.

Note that, as @Nawaz said, the one that works invokes undefined behavior, as would the one that doesn't work in the hypothetical even that it did.


As some say, ++++i is accepted by your compiler, but when it's evaluated, it produces undefined behavior in C++03.

Note that simply saying sizeof(++++i) is fine, because nothing is evaluated. Saying ++++i is fine in C++11 even if it's evaluated.


To answer this from the "what you want to do" view: there is no point to calling i++++ to start with, because i++ does not return a reference to the incremented i variable, but the value i had before it was incremented. So i++++ would essentially do this:

  1. Copy i to a temporary variable t
  2. Increment i
  3. Copy t to a temporary variable u
  4. Increment t
  5. Throw away both t and u

So all that remains would be one increment of i.

On the other hand, ++++i does simply

  1. Increment i
  2. Increment i, again

and that can indeed be useful, not so much in an integer type but certainly when i is a non-random-access iterator, because then you can't rely on i+=2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜