| operator, operator ++ and I
The problem is that with using w++|z++
you first use the value w
and ORing which is at the current value z
and then increment each one. Use instead ++w|++z
and the numbers will increase first and then be used.
int main()
{
int x = 10;
// prints 10
printf("%d\n", x++);
// prints 11
printf("%d\n", x);
x = 10;
// prints 11
printf("%d\n" ++x);
// prints 11
printf("%d\n" x);
}
You can do the same with --x
and x--
. See this important question for more information .
source to share
x++
increases x
but evaluates the old value w
.
So, w++|z++
evaluates as 3|7
(which appears to be 7 in your implementation) and increases w
and z
as a side effect.
If you want the behavior you expected, you could use the prefix operator ++x
that increments it x
and evaluates to a new value x
.
source to share
You've probably misunderstood the operator post-increment
, which is very common among newbies, so don't worry. Over time, you will fix it.
Take a look at the word post-increment
. It has a word post
in it that usually means after
. This means that the increment will happen, after
everything else is done. This is how I remember it.
So, if you look at your program now -
int main()
{
int w=3, z=7;
printf("%d\n", w++|z++);
}
then it becomes clear that after the execution of the function itself printf
, the increment is performed. Thus, you get the value w
and z
as 3
and 7
, accordingly, when evaluating the expression of the second argument printf
.
The official C ++ 11 standard, (§5.2.6, final version) says -
The value of the postfix ++ expression is the value of its operand. [Note: the resulting value is a copy of the original note - end of note
Thus, this means that the value of the postfix expression w++
is the value of the operand itself, that is, the value w
that is 3, and the value of the second expression z++
will be 7. These values will then be used in the calculation 3|7
, after which the variables will be incremented.
source to share