Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using true and false in C

Tags:

c

coding-style

As far as I can see there are 3 ways to use booleans in c

  1. with the bool type, from then using true and false
  2. defining using preprocessor #define FALSE 0 ... #define TRUE !(FALSE)
  3. Just to use constants directly, i.e. 1 and 0

are there other methods I missed? What are the pros and cons of the different methods?

I suppose the fastest would be number 3, 2 is more easily readable still (although bitwise negation will slightly add to overhead), 1 is most readable not compatible with all compilers.

like image 205
Tom Avatar asked Feb 12 '10 18:02

Tom


People also ask

Can you use true and false in C?

Boolean Variables and Data Type ( or lack thereof in C ) A true boolean data type could be used for storing logical values, and would only have two legal values - "true", and "false". C does not have boolean data types, and normally uses integers for boolean testing.

Is there boolean in C?

In C, Boolean is a data type that contains two types of values, i.e., 0 and 1. Basically, the bool type value represents two types of behavior, either true or false. Here, '0' represents false value, while '1' represents true value. In C Boolean, '0' is stored as 0, and another integer is stored as 1.

What is boolean in C language?

A boolean is a data type in the C Standard Library which can store true or false . Every non-zero value corresponds to true while 0 corresponds to false . The boolean works as it does in C++.

What is true and false in programming?

A Boolean variable has only two possible values: true or false. It is common to use Booleans with control statements to determine the flow of a program. In this example, when the boolean value "x" is true, vertical black lines are drawn and when the boolean value "x" is false, horizontal gray lines are drawn.


1 Answers

Just include <stdbool.h> if your system provides it. That defines a number of macros, including bool, false, and true (defined to _Bool, 0, and 1 respectively). See section 7.16 of C99 for more details.

like image 87
Chris Jester-Young Avatar answered Sep 25 '22 04:09

Chris Jester-Young