Is it safe to compare a boolean variable with 1 and 0 in C, C ++?

Consider the code

bool f() { return 42; }

if (f() == 1)
    printf("hello");

Does C (C99 + with stdbool.h) and C ++ standards mean that "hello" will be printed? Whether there is a

bool a = x;

always equivalent

bool a = x ? 1 : 0;
+4
source share
4 answers

In C ++ bool, it is a built-in type. Conversions of any type in boolalways give false(0) or true(1).

Prior to the 1999 ISO ISO standard, C had no built-in Boolean type. It was (and still is) for programmers to propagate their own Boolean types, for example:

typedef int BOOL;
#define FALSE 0
#define TRUE 1

or

typedef enum { false, true } bool;

1 , 0 1, 0 1 .

C99 _Bool, , , bool ++; bool, #include <stdbool.h>.

C ++ , undefined, , 0 1, bool. , :

bool b;
*(char*)&b = 2;

() 2 b, ++ , 0 1; , b == 0 b == true, .

:

  • , bool.
  • bool 0, 1, false true.

:

bool f() { return 42; }

, ++, C <stdbool.h>, true , , 1, 42 bool 1.

if (f() == 1)
    printf("hello");

- bool, "hello".

. f() bool, . (, , ) :

if (f())
    printf("hello");

f() == 1 , (f() == 1) == 1).

, -, , , :

if (greeting_required())
    printf("hello");
+2

. . "0" , int , f() true ( "1" ). 42, "return 42;".

+2

b c ( , stdbool.h), _Bool, 0 1.

++ f() f() == 1 int 1 .

, ,

bool f() { return 42; }

if (f() == 1)
    printf("hello");

.

+2

The only real trick I know is useful in pre-C99 environments is double negation

int a = 42;
if ( (!!a) != 0 ) printf("Hello\n");

this will print Hellobecause the result of the operation !!is a boolean, which true, when the value is nonzero, falseotherwise. But it will cost you 2 negatives to get the logical value you need, in modern standards it is redundant because you get the same result without !!, and this is the result provided by the language.

0
source

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


All Articles