Sunday, July 14, 2013

Program with Increment Operators in printf()

We have observed a program on Increment Operators when assigned to variable. If not, click here.
We have clearly understand how to analyze the pre-Increment and post-Increment Operators in such a case and ho w the values are manipulated when it is such a case. But what happens when we use the same expression in printf(). Does the result is same or any change occurs?

Consider the following example,

  1. #include<stdio.h>
  2. main()
  3. {
  4. int a=1,b=1,c;
  5. c=a + ++a + ++a;
  6. printf("%d %d\n",c,a);
  7. printf("%d %d\n",b+ ++b + ++b ,b);
  8. return 0;
  9. }

Check out the output of the above program, is that the same you have expected? The output will be like this
9 3
7 1 
Confused why there is a difference in between both the results???
Observe the analysis given below and understand the scenario.

We already how to solve the expression when assigned to a variable. But this is not the case with the printf(). This is because, printf() gets parallel execution. So it takes the values currently existing immediately.

So if we take Line 7
b+ ++b + ++b, it first goes to pre-increment operators and executes them first. In the first execution,

  • b + 2 + ++b

We expect the next execution to be ++b, but as it is in printf(), it gets executed parallel and takes the b value as it is in the left position.

  • 2+2+ ++b
And in the next step as b is incremented, ++b is changed to a value 3.
Hence the result is 7.

If you are not convinced with the above analysis, please do check by changing the line 7, with these two expressions
  • ++b + b + ++b     - Result is 7
  • ++b + ++b + b     - Result is 8
In the last case as the b is placed at the right most position, the expressions before it are solved and then the b. Hence the value changes.

So, we take a look at what happens a post-increment is involved in the expression.

Take the same example, just replace the Line 7 with the line
printf("%d %d", b+ ++b + b++ + b++,b);
Now take a look at the following analysis,

Solving the equation step by step.
As we already know, how does the solvation starts,

  • b+ 2 + b++ + b++;
In the next step, 
  • 2 + 2 + b++ + b++;
In the next step, as it is post increment, 
  • 2 + 2 + 2 + b++;
Now, with the next execution, as it is a printf(), parallel execution takes place. So post-increment in the previous step has taken place. So the value of b is now, 3
Hence in the next step,
  • 2 + 2+ 2+ 3;
After this step, again b increments by 1.
Thus the final result is 9.

This is how the equation gets solved. In the above example, you might have wondered that b value is not changing while printing. This is because of parallel execution. Write a new printf() printing b value in the next line of the expression. You will get the updated b value.

If you still have any doubts, feel free to contact me.