1 Replies - 838 Views - Last Post: 01 April 2007 - 03:48 AM Rate Topic: -----

#1 prannoy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 01-April 07

please explain this TC++ output

Posted 01 April 2007 - 03:31 AM

this is a code which i met by. The question is to find the output. but the one i got by myself had little resemblence with that given by the computer. i asked my teacher my friends. but none of them could give a sensible reason. i reckon there could be some wierd rearrangement or precedence rules in Turbo C++ which i am not aware of.

plz give it a try. and dont forget to post some replies.

the code is:
void main()
{ int x[]= {10,20,30,40};
int *p,*t,**q;
p=x;
t=x+1;
q=&t;
cout <<*p<<'\t'<<**q<<'\t'<<*t++;
}






so got 10 20 20 eh?

but sorry , the computer gives me
10 30 20

thanx for posting a reply!!

Is This A Good Question/Topic? 0
  • +

Replies To: please explain this TC++ output

#2 horace  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 291
  • View blog
  • Posts: 1,900
  • Joined: 25-October 06

Re: please explain this TC++ output

Posted 01 April 2007 - 03:48 AM

the probelm is you do not know when the ++ operator in the expression *t++ takes effect. In addition to evaluating the expression *t, the value of the variable in memory is altered (this is called a side effect). However, you do not know when this is done - it may be immediatly after evaluating *t or it may be saved until the next sequence point (in this case the ; ).
Thus it may be after the expression **q is evaluated and
you get
10 20 20
or before and you get
10 30 20

In practice do not use a variable more than once in an expression if one (or more) of the references has ++ or -- operators attached to it. You will get different results with different compilers.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1