Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using == outside of an if statement?

Tags:

c++

c

I've only ever seen "==" being used inside an if statement. So how does "==" work in this context?

a = 5;
b = (a == 18 % 13);
like image 415
Kyle Morgan Avatar asked Dec 20 '22 14:12

Kyle Morgan


2 Answers

If b is a bool, you can assign the result of an expression to it. In this case, if the condition a == 18 % 13 holds, b will become true, otherwise false.

Basically,

a == 18 % 13 - would yield b = true or b = 1

and

a != 18 % 13 - would yield b = false or b = 0

depending on the type of b.

like image 189
Luchian Grigore Avatar answered Dec 23 '22 04:12

Luchian Grigore


This

a == 18 % 3

is equivalent to

a == (18%3)

since the modulus operator % has higher precedence than the equality operator ==.

This expression evaluates to true or false (actually, true in this case). So you are assigning the result of that to variable b. b itself could be a bool or anything that can be converted from bool.

like image 45
juanchopanza Avatar answered Dec 23 '22 04:12

juanchopanza