Using == outside the if statement?

I only ever saw that "==" is used inside an if statement. So how does "==" work in this context?

a = 5; b = (a == 18 % 13); 
+4
source share
4 answers

If b is a bool , you can assign the result of the expression to it. In this case, if the condition a == 18 % 13 is fulfilled, 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 type b .

+7
source

it

 a == 18 % 3 

equivalently

 a == (18%3) 

since the module operator % has higher priority than the equality operator == .

This expression evaluates to true or false (in fact, true in this case). So you assign the result of this variable to b . b could be bool or anything that could be converted from bool .

+4
source

Ok, break it.

The question arises:

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

Let's start with the brackets. The% function, called the module operator, gives you the remainder of the division of two numbers. So, 18/13 gives you 1 remainder of 5. So:

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

now the equivalence operator == can only return true or false, 1 or 0. This is the same as a query if the left operand is equivalent to the correct operand. In this case:

  5 == 5; returns true or 1; 

Therefore, b = 1;

+1
source

C and C ++ are not high-level. They do not have a true Boolean type (although in C ++ and C99 there are typedefs to provide an integer type of small width to act as a boolean), therefore any nonzero integer, floating point or pointer value is treated as a boolean value true and zero as false As a consequence, logical expressions are evaluated as 1 (true), and 0 (false) and therefore can be assigned to an integer.

-1
source

Source: https://habr.com/ru/post/1440337/


All Articles