Why does num1++
not increment in the printf()
?
int num1 = 1;
printf("num1=%d", num1++);
Why does this print num1=1
instead of num1=2
?
Why does num1++
not increment in the printf()
?
int num1 = 1;
printf("num1=%d", num1++);
Why does this print num1=1
instead of num1=2
?
The ++
does increment the operand ... but in its postfix form, it evaluates to the value before incrementing.
++num1
instead would evaluate to the value after incrementing.
Because the expression
num1++
evaluates to num1
.
You may want to do:
++num1
which evaluates to num1 + 1
.
Note however that both expressions increment num1
by one.
Evaluating num1
in the next statement evalutes to the incremented value.
In C, why doesn't num1++ increment in the printf()?
num1++
does increment num1
but it evaluates to num1
and that evaluation is what you are passing to printf()
.
It comes from the fact that the ++ is after the variable, this will solve your problem
printf("num1=%d", ++num1);
The way you did your variable will be incremented after printing out its content, so if you do another printf on this variable you should have the right value, by putting it in the prefix way, it will increment the variable before outputting it
The postfix ++
operator evaluates to the current value of the operand, then it increments it. If you call printf
again with num1
as the argument, you would see the effect of the increment.
From section 6.5.2.4 of the C standard:
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).
If you used the prefix ++
operator, i.e. ++num1
, the increment would be reflected in the output.
Because having the ++ at the end of the variable causes the increment to happen after the operation. Adding the ++ before the variable will do the addition before the operation.