# evaluate it

Discussion in 'C++' started by ashim.seth@gmail.com, Jul 5, 2005.

1. ### Guest

hey people i was just testin this:
int i=5,j;
j=i++ + ++i;
cout<<j;

and then...

int i=5;
int j= i++ + ++i;
cout<<j;

both givin different results
y?
plz help

, Jul 5, 2005

2. ### Victor BazarovGuest

wrote:
> hey people i was just testin this:
> int i=5,j;
> j=i++ + ++i;
> cout<<j;
>
>
> and then...
>
> int i=5;
> int j= i++ + ++i;
> cout<<j;
>
>
> both givin different results
> y?
> plz help

V

Victor Bazarov, Jul 5, 2005

3. ### Peter JulianGuest

<> wrote in message
news:...
> hey people i was just testin this:
> int i=5,j;
> j=i++ + ++i;
> cout<<j;
>
>
> and then...
>
> int i=5;
> int j= i++ + ++i;
> cout<<j;
>
>
> both givin different results
> y?
> plz help
>

The results are irrelevent. Since you are refering to the same variable in
that compound statement, the standard does not guarentee when, how or
whether the variable i gets incremented. In fact, the standard has a
requirement that the said variable be only modified once in between sequence
points.

Try:

#include <iostream>

int main()
{
int i = 5;

std::cout << "i = " << i << "\n";

int j(i++);

std::cout << "i = " << i << "\n";
std::cout << "j = " << j << "\n";

j += (++i);

std::cout << "i = " << i << "\n";
std::cout << "j = " << j << "\n";

return 0;
}

/*
i = 5
i = 6
j = 5
i = 7
j = 12
*/

Peter Julian, Jul 5, 2005