Kyle Morgan
Kyle Morgan

Reputation: 680

Using == outside of an if statement?

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

a = 5;
b = (a == 18 % 13);

Upvotes: 4

Views: 440

Answers (4)

Patrick Borkowicz
Patrick Borkowicz

Reputation: 1216

Ok, let's break it down..

The question is:

a = 5, b=(a==18%13); // What is b?

We'll start with the brackets. The %, called the modulus operator, gives you the remainder of dividing the two numbers. So 18/13 gives you 1 remainder 5. So:

18%13 = 5;

// so now we have
b=(a==5);

now the equivalency operator == can only return true or false, 1 or 0. It's the same as asking if the left operand is equivalent to the right operand. In this case:

 5 == 5; returns true or 1;

Therefore b = 1;

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258558

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.

Upvotes: 7

juanchopanza
juanchopanza

Reputation: 227370

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.

Upvotes: 4

user529758
user529758

Reputation:

C and C++ are not that high-level. They have no true boolean type (although in C++ and C99 there are typedefs for providing some small-width integer type to act as a boolean), so any nonzero integer, floating-point or pointer value is treated as boolean true and zero as false. As a consequence, logical expressions evaluate to either 1 (true) or 0 (false) and thus can be assigned to an integer.

Upvotes: -1

Related Questions