I don't understand why a equals 1 and b equals 0 at the end. They should be the same in my view. Thanks in advance.
#include "stdio.h"
int main()
{
int a=0;
int b=0;
a++;
printf("a=%d,b=%d",a,b++);
return 0;
}
I don't understand why a equals 1 and b equals 0 at the end. They should be the same in my view. Thanks in advance.
#include "stdio.h"
int main()
{
int a=0;
int b=0;
a++;
printf("a=%d,b=%d",a,b++);
return 0;
}
Before this call:
printf("a=%d,b=%d",a,b++);
the variable a was already incremented by:
a++;
However in the pointed-to call of printf
, the value of the post-increment expression b++
is the value of the variable b
before its increment. So 1 and 0 are output.
If you want to get the output 1 and 1, then use the pre-increment expression with the variable b
like:
printf("a=%d,b=%d",a,++b);
From the C Standard (6.5.2.4 Postfix increment and decrement operators)
2 The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it)...
The operation b++
sends b
to printf
before doing the increment. a
is incremented before printf
is called
printf("a=%d,b=%d",a,b++);
Is logically equivalent to:
printf("a=%d,b=%d",a,b);
b++;