Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison of bool data types in C++

The bool data type is commonly represented as 0 (as false) and 1 (as true). However, some say that true values can be represented by a value other than 1. If the later statement is true, then the following expression may be incorrect.

bool x = 1;
if (x==1)
    Do something..

I am wondering if the following statements would work as desired and expected on commonly used compilers.

  1.  

    bool x = 1;
    if (x==1)
        Do something.
    
  2.  

    bool y = 0;
    if (y>0.5)
        Do something..
    
  3.  

    bool z = 1;
    if(z>0.5)
        Do something...
    
like image 660
rezabakhsh Avatar asked May 20 '19 09:05

rezabakhsh


People also ask

Is there any bool data type in C?

C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.

How can I compare two boolean values in C++?

Use with Relational Operators: In Java, boolean variables cannot be used with the relational operators like <, >, <=, and >= , whereas in C++, they can be used in this manner . However, they can be used with == and != operators in both Java and C++ .

How many bytes is a bool in C?

bool The bool type takes one byte and stores a value of true (1) or false(0). The size of a bool is 1 true 1 1 1 false 0 0 0 Press any key to continue . . . int is the integer data type. Integers are represented in binary format.

Where is bool defined C?

bool exists in the current C - C99, but not in C89/90. In C99 the native type is actually called _Bool , while bool is a standard library macro defined in stdbool. h (which expectedly resolves to _Bool ).


1 Answers

§4.5 of the C++ standard says:

An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.

regarding 2 and 3, type conversion takes place so the statements will work as desired

like image 170
akib khan Avatar answered Oct 13 '22 00:10

akib khan