Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 2 + 1 & 0 result is 0?

Tags:

c++

visual-c++

In VC2008, I typed this code:

int a = 2 + 1 & 0;

and this expression's result is a = 0

Why the result is 0 but not 2?

like image 563
Spark Avatar asked Dec 29 '11 15:12

Spark


2 Answers

Because the & operator is evaluated after the + operator and 3 & 0 equals 0.

Of course you can place braces around the expressions to change the evaluation order. E.g:

int a = 2 + (1 & 0);
/* a == 2 */
like image 134
Constantinius Avatar answered Oct 30 '22 14:10

Constantinius


The + has greater precedence than the &. Here is a complete table of operator precedence.

like image 36
Petar Minchev Avatar answered Oct 30 '22 15:10

Petar Minchev