Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition assignment to boolean

Tags:

c++

c

Emulating booleans in C can be done this way:

int success;
success = (errors == 0 && count > 0);
if(success)
   ...

With stdbool.h included following could be done:

bool success;
success = (errors == 0 && count > 0) ? true : false;
if(success)
   ...

From what I understand logical and comparison operators should return either 1 or 0. Also, stdbool.h constants should be defined so that true == 1 and false == 0.

Thus following should work:

bool success;
success = (errors == 0 && count > 0);
if(success)
   ...

And it does work on compilers that I have tested it with. But is it safe to assume it is portable code? (Assume that stdbool.h exists)

Is the situation different on C++ compilers as bool is internal type?

like image 648
user694733 Avatar asked Feb 01 '13 08:02

user694733


People also ask

How do you give a Boolean value in if condition?

An if statement checks a boolean value and only executes a block of code if that value is true . To write an if statement, write the keyword if , then inside parentheses () insert a boolean value, and then in curly brackets {} write the code that should only execute when that value is true .

Can you assign a variable to a Boolean?

You can use the bool method to cast a variable into Boolean datatype. In the following example, we have cast an integer into boolean type. You can also use the bool method with expressions made up of comparison operators. The method will determine if the expression evaluates to True or False.

What is a condition in Boolean?

The condition is a Boolean expression: an expression that evaluates to either true or false . Boolean values are another type of data type in programming languages, and they can only ever hold true or false.

What is assignment in Boolean?

A value that is assigned to a Boolean column or variable must be a Boolean value, or a string or numeric representation of a Boolean value. See Boolean values for details. The result of the evaluation of a search-condition can also be assigned.


1 Answers

It is safe to assume. In C99, upon conversion to the _Bool type, all non-zero values are converted to 1. This is described in section 6.3.1.2 in the C99 standard. The equality and relational operators (e.g. ==, >=, etc) are guaranteed to result in either 1 or 0 as well. This is described in section 6.5.8 and 6.5.9.

For C++, the bool type is a real Boolean type where values are converted to true or false rather than 1 or 0, but it is still safe to assign the result of an == operation etc. to a bool and expect it to work, because the relational and comparison operators result in a bool anyway. When true is converted to an integer type it is converted to 1.

like image 170
dreamlax Avatar answered Sep 24 '22 17:09

dreamlax