Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do C++ operators work

Given that x = 2, y = 1, and z = 0, what will the following statement display?

printf("answer = %d\n", (x || !y && z));

It was on a quiz and I got it wrong, I don't remember my professor covering this, someone enlighten me please... I know the answer I get is 1, but why?

like image 433
mayotic Avatar asked Sep 28 '10 03:09

mayotic


People also ask

How does an operator work?

The logical AND operator ( && ) returns true if both operands are true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool . Logical AND has left-to-right associativity.

What is << in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

How does C do order of operations?

The circled numbers indicate the order in which C evaluates the operators. The multiplication, remainder and division are evaluated first in left-to-right order (i.e., they associate from left to right) because they have higher precedence than addition and subtraction. The addition and subtraction are evaluated next.


2 Answers

The expression is interpreted as x || (!y &&z)(check out the precedence of the operators ||, ! and &&.

|| is a short-circuiting operator. If the left operand is true (in case of ||) the right side operand need not be evaluated.

In your case x is true, so being a boolean expression the result would be 1.

EDIT.

The order of evaluation of && and || is guaranteed to be from left to right.

like image 79
Prasoon Saurav Avatar answered Sep 19 '22 17:09

Prasoon Saurav


If I'm not mistaken, it will print 1. (Let's assume short circuiting is off)

(x || !y && z) or (true || !true && false) will first evaluate the ! operator giving (true || false && false)

Then the &&: (true || false)

Then || : true

Printf will interpret true in decimal as 1. So it will print answer = 1\n

like image 25
JoshD Avatar answered Sep 17 '22 17:09

JoshD