Can SomeBody Explain to Me...

Question # 1:
int b[]={1,2,3,4,5};
int j=0;
for(int i=0; i < 5;++i)
cout<< b[j++] << " "<<j<<" "<<b[j] <<" "<<endl;

The output of this program is :
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5

As it is a post-increment operator the value of j is incremented but still b[j] is showing the previous index value...
Question # 2:
L1:int b[]={1,2,3,4,5},c[5],d[5];
L2:int j=0;
L3: for(int i=0; i < 5;++i)
L4:{
L5: c[j]= (i+1)*(i+1);
L6: d[j]= c[j++];
L7:}

for(int i=0; i < 5;++i)
cout<< c[i] << " "<<d[j] <<" "<<endl;

The output of this program is :
1 1
4 4
9 9
16 16
25 25

As the assignment operator has left to right assosciativity why then result look like this...????

Thanks in Advance..
#1
The << operator doesn't guarantee that the expressions are evaluated from left to right
( http://www.cplusplus.com/forum/beginner/7322/#msg33900 )
Last edited on
1. The moment at which the increment is done is undefined.
In some compilers
b=a++ + a;
is the same as
b=a+a;
a++;
While in others, it's the same as
b=a;
a++;
b+=a;

2. Huh?
1
2
3
4
//j==5?
for(int i=0; i < 5;++i)
    cout<< c[i] << " "<<d[j] <<" "<<endl;
//j==5? 

That's giving you 1, 4, 9, 16, 25 for d[j=5]?

Did you know this is valid?
for (int i=0,j=n;i<n;i++,j--)
Here is the exact Question
Question # 2:
L1:int b[]={1,2,3,4,5},c[5],d[5];
L2:int j=0;
L3: for(int i=0; i < 5;++i)
L4:{
L5: c[j]= (i+1)*(i+1);
L6: d[j]= c[j++];
L7:}

for(int i=0; i < 5;++i)
cout<< c[i] << " "<<d[i] <<" "<<endl; // it is i not j it was just typing mistake.

The output of this program is :
1 1
4 4
9 9
16 16
25 25

As the assignment operator has left to right assosciativity why then result look like this...????
[] has a higher precedence order than =. This is the resolved order of operations (I'm using & to refer to the result of a step):
1. [](d,j)
2. [](c,j)
3. =(&1,&2)
4. ++(j)

Remember that expressions are always evaluated from left to right regardless of their operators.
Topic archived. No new replies allowed.