Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator "&" cannot be applied to byte, int, boolean

Upon my previous question about how to compare if combined bits contain a specific bit I am running into this error.

    int flag1 = 1 << 0;
    int flag4 = 1 << 5;

    int combined = flag1 | flag4;

    if (combined & flag1 == flag1) // <-- Operator & cannot be applied to int, boolean

If I cast the flags to byte the error replaces int with byte.

like image 335
Madmenyo Avatar asked Mar 21 '16 08:03

Madmenyo


Video Answer


1 Answers

The compiler sees the binary operator & in your if statement, treats it as logical AND (since it expects an expression that returns a boolean), and checks the types of the arguments.

It encounters one int argument - combined - and one boolean argument - flag1 == flag1. Since it expects two boolean arguments (the & operator cannot be applied to an int and a boolean), it gives an error.

Add parentheses in order for the operators to be evaluated in the desired order :

if ((combined & flag1 ) == flag1)
like image 89
Eran Avatar answered Oct 12 '22 09:10

Eran