Why ++++ am I regular but am ++++ not regular in C ++?

When I use i++++ , give a compilation 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 using ++++i works. Can someone explain to me why ++++i regular, but i++++ not regular?

Thanks.

+4
source share
5 answers

Since type x is a built-in primitive type, both expressions cause undefined behavior , since both try to change the same object twice between two points in a sequence.

Do not use any of them.

Read this FAQ:

undefined behavior and sequence points


However, if type x is a user-defined type, and you overloaded operator++ for both expressions, then both will be clearly defined .

To do this, see this topic for explanations and details:

undefined behavior and sequence points are reloaded

+13
source

The C ++ standard in section 5.2.6 says that the result i ++ is a mutable value of lvalue, and in 5.3.2 that the result ++ i is a mutable value of l. This may help explain why I ++++ and ++++ are not required to generate diagnostics and may sometimes work.

However, ++++ I change I twice between the previous and next points in the sequence, so the result will still be undefined. ++++ I am allowed to work, but this is not necessary.

Luckily for you, your compiler has diagnosed me as ++++.

+6
source

Since the conceptual "signatures" of the operators:

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

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

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

+5
source

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

Please note that simply saying sizeof(++++i) excellent because nothing is evaluated. Saying ++++i excellent in C ++ 11, even if it has been evaluated.

+3
source

To answer this from the β€œwhat you want to do” view: it makes no sense to call i++++ for a start, because i++ does not return a reference to the variable i , but the value of i was before it was incremented. So i++++ will essentially do this:

  • Copy i to temporary variable t
  • Increment i
  • Copy t to temporary variable u
  • Increment t
  • Drop both t and u

So all that remains is one increment i .

++++i , on the other hand, just makes

  • Increment i
  • Increment i , again

and it really can be useful not so much in the integer type, but, of course, when i is an iterator of nonrandom access, because then you cannot rely on i+=2 .

+1
source

All Articles