Search code examples
cpostfix-operator

Unable to understand the output of program in C


EDIT: This question is not duplicate as the behavior is not undefined in this case.

Why does the below program print the output as 231 in first line?

I have two doubts regarding this:

  1. As I am doing postfix increment the value of x shouldn't have been increased before the I call max function. So the output should have been 1 in the first place instead of 2 according to me. What am I missing?

    #define prn(a) printf("%d",a)
    #define print(a,b,c) prn(a), prn(b), prn(c)
    #define max(a,b)  (a<b)? b:a
    
    main()
    {
        int x=1, y=1;
        print(max(x++,y),x,y);
        printf("\n");
        print(max(x++,y),x,y);
    }
    

    Output:

    231
    451
    
  2. The postfix operation occurs after execution of the statement? Consider the example below.

    int main()
    {
        int x = 0, y = 1;
        int a = x++ /*x is incremented hereafter?*/+ y;             // line 1
        /* Or x is incremented now after execution of above line?*/ // line 2
        int b = 0;
    }
    

Solution

  • let me take this line

                   print(max(x++,y),x,y);
    

    One important point to note is that the C preprocessor is a macro preprocessor (allows you to define macros) that transforms your program before it is compiled. These transformations can be inclusion of header file, macro expansions etc.

    All preprocessing directives begins with a # symbol. For example,

                    #define PI 3.14
    

    tells the compiler to replace the value PI with 3.14 where ever it sees.

               c source code->preprocessor->compiler
    

    therefore print(max(x++,y),x,y) is expanded in macro to

               1.      prn((x++<y) ? y:x++), prn(x), prn(y) 
    
            2. printf("%d",(x++<y)? y:x++), printf("%d",x), printf("%d",y);.
    

    here it gets processed you can check two things carefully here

    while checking

                   x++<y ,the x++ value is 1
    

    then after that the x value becomes 2

    so 2 is printed

    and then while printing also we wrote x++ that means here x++ VALUE IS 2 but

    after that x value is 3

    so 3 is printed and it follows y as 1

    that 's how it works

    2.TO give you a great intuition on preincrement and post increment

    let me take an example

                   int x=2;//value of x is 2
    
                   x++;//here x++ value is 2
    

    after this line execution x value changed to 3

                   ++x//here x++ value is 4 and also x value is 4.