Tuesday 7 October 2014

Increment operator in c

Are you ready for some serious brain storming?
Here it goes my first post.

1. What would be the output of this program while running with the gnu gcc compiler?


#include<stdio.h>

int main(int argc, char * argv[]){

      int z=2;
      int y=2;
   
      z=z++;
      y=++y;
      printf("%d  %d",z,y);
 return 0;
}

Please Before proceed to answer just think for a minute.
Think ::::


This Space is left intentionally.









Although this is undefined behavior due to absence of sequence point. I will define sequence point in my future posts. But here I am presenting one of the reasons of getting this output.




Answer is  : 2 3

Reason is : For understanding the reason behind this we have to understand the execution sequence of instruction z=z++;

For evaluation of a expression compiler generates a temporary variable and evalute the expression and store the value in the temporary variable which in the given expression is 2 because postfix operator executes after the expression is evaluated. So till now the temporay variable has value 2 
and now z becomes three due to posfix operator. And then the temporary variables value is assigned to the variable which is on the left side of the = operator which here is z itself so value 2 is assigned to z again.
Finally the value of z becomes 2.

Similarly for the value of y first expression is evaluated and in this pre increment is also evaluated so value of y becomes 3 and the value of temporary variable is also becomes 3 and now this temporary variable's value is assigned to y.
Finally the value of y becomes 3.

2 comments:

  1. The solution will be undefined due to absence of a sequence point. Hence, the answer printed will depend upon the compiler you're using.

    for further details: http://stackoverflow.com/questions/3575350/sequence-points-in-c

    P.S.- Glad that you've taken an initiative. All the best :)

    ReplyDelete
  2. I know this is undefined behavior. I just present one of the reason for getting that answer in some of the compilers.
    Thanks for pointing out. I presume that people know about that.
    And yes every complex output varies with the compiler. So output may vary.
    This is just a reason for that output.

    ReplyDelete

Related Posts

Related Posts Plugin for WordPress, Blogger...