Tuesday, July 14, 2009

Solve this...any c++ programmers out there..?

a simple c++ program--%26gt;


main()


{ static int a[]={97,98,99,100,


101,102,103,104};


int*ptr=a+1;


print(++ptr,ptr--,ptr,


ptr++,++ptr);


}


print(int *a,int *b,int *c,int *d,int *e)


{


printf("\n%d %d %d %d %d",*a,*b,*c,*d,*e);


}





help me with its o/p....i m not getting it..


its showing 100 100 100 99 99


but i thought 99 99 98 98 99

Solve this...any c++ programmers out there..?
This is due to the fact that the compiler execute printf from right to left internally but prits the output Left to Right. So if you look at the printf this way you will understand the output. i.e





1st execution will be ++ptr


2nd execution will be ptr++ and so on......
Reply:The print( ) statement with all the incremented and decremented ptr arguments can give different results on different C compilers, because there is no rule for the compiler about the order in which the arguments should be evaluated.





b, c, d and e are not declared, so the program should not compile anyway, and they are not initialised, so if it somehow compiles, the results of their print( ) statements could be anything.


No comments:

Post a Comment