incrementing variables in C++

Hello,

what is the result of the below, and how does it work?

int i = 5;
cout << i++ * ++i << endl;
cout << i << endl;

Compile it and find out. Because this looks like a homework assignment.

No, this is not a homework assignment.

int i = 5;
cout << i++ * ++i << endl;
cout << i << endl;

The integer is 5.

++ is an increment to the integer and then adds 1 to the variable if it precedes the variable. If it follows the value of the variable returns the value before it was incremented.

Most likely the value of that is 30 (5*6) but yeah, learn to compile :slight_smile:

please see Sequence point - Wikipedia, the free encyclopedia

If this is not a homework, can we know the intention behind this question?
Are you looking for explanation on how it works? Please clarify

looking for an explanation on how it works.. as my first post states.

In short: it sets the variable i to 5, increments it twice while multiplying, outputs the result of the multiplication, and then outputs the value of i.

If you need more information, we need to be sure that it's not homework, or post in this forum (because of rule 6, to which you agreed when registering)

OK here is what happens:

  1. It assigns 5 to i,
  2. Then, i++ increases i to 6 before multiplication,
  3. Now, i with its value being 6, is multiplied by ++i,
  4. ++i means use the value of i, then, increase it, so it will use 6 here, too.
  5. After the multiplication is done, i is incremented to 7, which is the value echoed by cout.

I hope it is clear now.
From my point of view, this is a drill or an exercise to explain precedence.

faizlo

Hello Milhan,
The post of faizlo will explain this as best someone can, but the result of this will be:

ubuntu@ubuntu-laptop:~$ ./test
36
7
ubuntu@ubuntu-laptop:~$

Thanks,
Nathan Paulino Campos

The outputs are 36 and 7 respectively.

Associativity is right to left in this statement. Hence

cout << i++ * ++i << endl;

is actually the same as

cout << ++i * i++ << endl;

The result of this operation is undefined.
g++-4.2 gives the following error message:
warning: operation on 'i' may be undefined
The reason for this is explained at
Sequence point - Wikipedia, the free encyclopedia

Interesting. g++ 4.4.0 does not give such a warning.