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?
CodePudding user response:
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!
CodePudding user response:
The issue here isn't the space in the second statement, it's the fact you have two of them. After the first statement (to be exact, after a
is called), the value of a
is incremented and is now 6. So a b
will clearly return 8
. If you omit the first printf
call and just call the second one, you'll get 7
as you expect.