clexical-analysispost-incrementlexical

Getting wrong output for a++ +b according to lexical analysis when the program is printed along with a+++b


I wrote the following C program to find the output for a+++b

#include<stdio.h>
int main()
{
    int a=5, b=2; 
    printf("%d",a+++b);
}

And I'm getting the output as 7 which is correct according to lexical analysis.

Apart from that I wrote a separate program to find the output for a++ +b

#include<stdio.h>
int main()
{
    int a=5, b=2; 
    printf("%d",a++ + b); 
}

For the above program again I'm getting output as 7 (which is again correct according to lexical analysis)

But when I wrote a program to print the outputs for both a+++b and a++ +b I'm getting different outputs

#include<stdio.h>
int main()
{
    int a=5, b=2; 
    printf("%d",a+++b); 
    printf("\n%d",a++ + b); 
}

The output is 7 for a+++b (which is correct) and 8 for a++ +b (which is wrong).

Can anyone point out the error in the third program?


Solution

  • a++ is post-fix increment. It evaluates to a and increments the variable a by 1 before the enclosing printf() is called in this case(*).

    So after the first printf() the value of a is 6.

    So what do you now expect from the second printf?

    Operators like post-fix ++ are expressions (have a value) and instructions (have an effect). They cause endless confusion bugs and undefined behaviour to novices and bite the most seasoned programmers on the ass from time to time.

    (*) These operators are useful and have their place but exactly when these operators take effect is complex sometimes counter intuitive and I recommend you don't use them in complex expressions to begin with or even ever. They're a bit of a throw back to when compilers didn't optimise code for you and the programmer had to help!