Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how is x&&y||z evaluated?

Given

int x=1,y=2,z;

Could you explain why the result for:

x && y || z 

is 1?

x && y = 1
x && y || z = 1
like image 548
Dan Dinu Avatar asked Sep 01 '11 08:09

Dan Dinu


4 Answers

x && y || z 

is equivalent to

(x && y) || z

if x=1 and y=2 then x&&y is 1 && 2 which is true && true which is true.

true || z 

is always true. z isn't even evaluated

like image 130
Armen Tsirunyan Avatar answered Oct 26 '22 02:10

Armen Tsirunyan


x && y || z => (x && y) || z => 1 || z => 1

like image 22
Paul Avatar answered Oct 26 '22 00:10

Paul


(bool)1 = true
(bool)2 = true

Uninitialized int refers to data that was saved in memory, where it is placed on stack... and it rarely is 0x00000000, and even if it was, true || false = true.

like image 22
Griwes Avatar answered Oct 26 '22 02:10

Griwes


The && operator has higher precedence than the || operator. See, e.g., this operators precedence table, numbers 13 and 14.

Your example evaluates as (x && y) || z. Thanks to the short circuiting rule, z is never evaluated because the result of x && y is already true.

like image 24
wilx Avatar answered Oct 26 '22 01:10

wilx