Monday, February 25, 2008

Question Set 3

Postfix Prefix Problem
main()
{
int x=10,y,z;
z=y=x;
y-=x--;
z-=--x;
x-=--x-x--;
printf("y=%d z=%d x=%d",y,z,x);
}

Output
y=0 z=2 x=6


Solution
questionSet3_prefix_postfix

Exception

The After execution (postfix) / before execution (prefix) rule, is not followed in printf expressions. For instance,

main()
{
int a=3,c;
c=a++ + ++a + a++;
printf("%d",c);
printf("\n%d",a++ + ++a + a++);
}

Now
c=a++ + ++a + a++;
follows the rule i.e. (here one prefix and two postfix)
step1: prefix ++a makes a = 4
step2: c= 4+4+4 = 12
step3: Two pending prefix operations make a = 6;

printf("\n%d",a++ + ++a + a++);
Operates in right to left order and Do not follows above rule) say exp X = a++ + ++a + a++

step1:
first a++ puts a=6 in the exp X at its place then a is incremented making it to 7
X = a++ + ++a + (6) , a = 7

step3: Now prefix increment ++a makes a equal to 8, Then puts the value in the exp X at its place.
X = a++ + (8) + (6), a=8

step3: Now leftmost a++ puts a=8 in the exp X at its place then a is incremented making it to 9
X = (8) + (8) + (6) , a= 9

so
printf prints 22 on the screen.

No comments: