Sunday, April 18, 2010

Predict the Output

int main()
{
int a=1;
a+=a++;
printf("%d",a);
a+=++a;
printf("%d",a);
return 0;
}

Output:
3 8

Logic:
a+=a++ is equal to a=a+a++;
watch out the value of 'a' in this expression.

a=a + a++
3  1   1
a+a=2 and the post increment will increment the value of 'a' so it will result in a=3.(to understand increment operator see this post also Lparts,Pre and post,Post 18).

Now we will consider the second operation i.e., a+=++a;. This expression is equal to
a=a+ ++a;
This expression is manipulated as follows:
a = a+  ++a;
8   4     4    
Pre increment will increment the value of a first so 'a' has now 4. and a+a is 8 is assigned to a. so a=a+a=8.

0 comments:

Post a Comment