| operator, operator ++ and I

I guess I'll get it 12

, not 7

.  w++

, It w

is 4

that 100

, and w++

, w

will 8

, 1000

; therefore w++|z++

will 100|1000 = 1100

be 12

.

What happened to me?

int main()
{
    int  w=3, z=7; 
    printf("%d\n", w++|z++);
}

      

+3


source to share


6 answers


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 .

+2


source


You are misunderstanding the postfix operator ++

. The value of the variable is used before the variable is incremented. Your analysis will be correct for the prefix ++

as in ++w|++z

.



+3


source


These are post increment statements; they take effect after the operation, so the operation uses 3 and 7.

+2


source


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

.

+1


source


You are doing post-increment ( i++

), which takes a value first i

and then increments its value.

If you want to achieve what you said in your question, do this: ++w | ++z

+1


source


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.

0


source







All Articles