C++. Operations of relations. Type bool




Operations of relations. Type bool


Contents


Search other websites:

1. Why use the operations of relations in the C/C++ language?

In C/C++ programs, the operations of relations are used to compare two values with each other. These values can be numbers, variables, constants, the results of evaluating expressions, and so on. Operations of relations returns one of two possible values:

  • true, if the result of the operation of relation is satisfied;
  • false if the result of the operation of relation is not satisfied.

The operations of relations are binary. They require two operands.

2. What operations of relations are supported by C/C++?

In the C/C++ programming language, the following operations of relations are supported:

> – more
< – less
>= – more or equal
<= – less or equal
!= – not equal
== – equally






3. Which C/C++ constructs can a operations of relations be used for?

Operations of relations can be used:

  • in cycles where there is a condition for the execution of a cycle;
  • in assignment operators that contain logical expressions (if you want to get the result of a complex logical expression);
  • in conditional operators ‘if’.

4. Examples of operations of relations

A code snippet, showing the use of relationship operations in a C/C++ program:

// operations of relations
int a, b;
bool res;

a = 9;
b = -100;
res = a > b; // res = True
res = false == true; // res = False

// ---------------
// conditional operator 'if'
res = false;
if (a>b)
    res = true; // res = true

res = a > b == 8; // res = false

a = 50;
b = 0;
res = a != b; // res = True

// The 'bool' type is an integer type
res = 8; // res = True
res = 0; // res = False

5. How is the bool type represented in C++ programs? How are the types of bool and int related?

The bool type is represented as an integer. If the value of a variable of type bool is nonzero, then it is considered equal to true. If the value of a variable of type bool is 0, then it is assumed to be false.

Similarly, if the value of an integer variable is not 0 (zero), then it is considered as ‘true’. If the value of the integer variable is 0, then it is equivalent to ‘false’.

Example.

// operations of relations
// the 'bool' and 'int' types
int a;
bool b;

a = 8;
b = a; // b = True

// using in the 'if' statement
b = false;
if (a)
    b = true; // at the output b = true


Related topics