Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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 throw back to when compilers didn’t optimise code for you and the programmer had to help!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading