Using true and false in C
Asked Answered
E

16

96

As far as I can see, there are three ways to use Booleans in C:

  1. with the bool type, from <stdbool.h> 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), and 1 is most readable not compatible with all compilers.

Egocentrism answered 12/2, 2010 at 18:15 Comment(10)
You actually think the compilers going to wait until runtime to negate a constant?Refugiorefulgence
To follow up so I don't seem like a jerk, no compiler will actually waste it's time doing that. Compilers are heavy optimizers, and if it knows the results will always be the same, it'll put that in there instead. It will never wait until runtime to evaluate int i = 12 + 3 * 4;; it'll just say int i = 24;. Worrying about performance like that a common problem, don't feel bad. Optimizations comes last, and when it does come you have to time your code and look at the assembly output, not guess. Even if it did cost a cycle, I'd go for the most readable solution. Only when it proved to be aRefugiorefulgence
problem would I switch to faster solution, timing them to make sure they were indeed faster. When given a choice between readability and a cycle, choose readability. :) It's easy to make good code fast, but hard to make "fast" code good.Refugiorefulgence
When using the macros, remember that (x == TRUE) is not the same as (x). The former is true only if x holds the value of TRUE. The latter is true for any non-zero value.Observer
+1 @Devon, most of the time I only use the constants as return values.Stereoscopy
I advise against defining special boolean macros; this only tempts novice programmers to write things like if(foo == TRUE) or if(foo == FALSE), which is an atrocity in most languages, but even more so in C, where any scalar value != 0 is considered to be true in boolean contexts; for similar, but less severe reasons, I dislike if(foo != NULL) and if(foo == NULL) for pointers; as this can't introduce bugs as a comparison to TRUE can, it's merely a matter of taste, but using if(foo) and if(!foo) for any scalar value is imo more in tune with the C language look-and-feelChlorophyll
https://mcmap.net/q/53575/-using-boolean-values-in-cSuspicion
"what is the best ..." is *always subjective, and too easily argumentative to be risked. I edited the question text to help, but even that isn't safe. Finally, I'm with jamesdlin...Howlend
@Refugiorefulgence actually I would expect this to be missed by compilers when the constant is used across compilation unit boundaries ("in a different C file"). Optimizing it out would require the code to be optimized after linking as the value can't be known during the compilation of the current compilation unit (before linking). Any ideas how compilers avoid this?Nertie
Umm... I'm no C expert but isn't !(FALSE) logical negation? Otherwise if ! were bitwise, it would evaluate to -1, no?Crockett
S
148

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.

Shawanda answered 12/2, 2010 at 18:16 Comment(1)
You can use _Bool without including stdbool.hChlorophyll
L
23

Just use 0 or 1 directly in the code.

For C programmers, this is as intuitive as true or false.

Lucchesi answered 12/2, 2010 at 18:22 Comment(9)
For C programmers, -1 is also true, since it is not a zero. For that matter, 42 and -234 are also true values. I've seen -1, -2 and other values as true. Some functions return 0 (zero) as successful. Hmmm, so much for consistency.Colleague
I usually just see 1 or -1 used as true values. -1 because it's all-ones in binary. I'd love to know where you found -2.Dripping
I agree with Thomas. The fact that 0 is used as an error code for "no error" (and often also as an int type) sometimes makes it non-obvious whether a value is supposed to be used in a boolean context.Suspicion
Think of a function returning 0 for no-error, as answering the question "did you have any problem?" - "0=false=no". int fail = close(fd); if (!fail) { great(); } else { weep(); }Payoff
@squelart: The problem is a lot of functions that return boolean values don't have that semantic and return a true value on success, false on failure. (For example, much of the Win32 API is designed this way.)Suspicion
You're right, the different return patterns are confusing. But if the initial developer used the above suggestion when first using a function (at which point the dev would know already, or read about, the return value), maintenance would hopefully be easier later on...Payoff
The pattern of returning 0 to indicate success is part of a larger pattern, as follows: a function returns a positive integer value (for example, count of bytes processed, or elapsed time, etc.) if it is successful. Failure is indicated by returning a negative integer. If we now apply this pattern to a function that only returns success or failure, we are left with -1 for failure and 0 for success. Many Linux/Unix system calls and library functions follow this pattern, so it's good to be familiar with it.Maund
Some values are not so true as if (0.4) and if (abs(0.4)) differ.Undercurrent
I do this sometimes: Positive : True / Success Codes 0 : Undefined / Uninitialized Negative: False / Failure CodesInferential
C
22

I usually do a:

typedef enum {FALSE = 0, TRUE} boolean;
Certiorari answered 12/2, 2010 at 18:22 Comment(3)
why do you explicitly set FALSE=0? Isn't the first element of an enum automatically 0?Dasheen
@Dasheen It's just in case they add FileNotFound to the front of that enum. ;-)Shawanda
@Dasheen It makes sense. Making sure that FALSE is 0, is the only important thing. TRUE can be whatever as long as it is different.Cheapskate
R
6

Whichever of the three you go with, compare your variables against FALSE, or false.

Historically it is a bad idea to compare anything to true (1) in c or c++. Only false is guaranteed to be zero (0). True is any other value.   Many compiler vendors have these definitions somewhere in their headers.  

#define TRUE 1
#define FALSE 0

This has led too many people down the garden path.   Many library functions besides chartype return nonzero values not equal to 1 on success. There is a great deal of legacy code out there with the same behavior.

Regulator answered 4/8, 2012 at 23:42 Comment(3)
I have noticed that comparisons against TRUE fail against uninitialized variables. It's better to initialize your booleans and compare against FALSE. An enum is better if you truly need three values; no, yes, and donotknow. Initialize the enum to donotknow. Don't treat the enum as if it were boolean. It isn't.Regulator
Why not #define TRUE !FALSE #define FALSE 0?Bug
That would be fine. It won’t fix the root problem with testing against TRUE.Regulator
C
5

With the stdbool.h defined bool type, problems arise when you need to move code from a newer compiler that supports the bool type to an older compiler. This could happen in an embedded programming environment when you move to a new architecture with a C compiler based on an older version of the spec.

In summation, I would stick with the macros when portability matters. Otherwise, do what others recommend and use the bulit in type.

Cinematography answered 12/2, 2010 at 18:19 Comment(0)
C
4

Any int other than zero is true; false is zero. That way code like this continues to work as expected:

int done = 0;   // `int` could be `bool` just as well

while (!done)
{
     // ...
     done = OS_SUCCESS_CODE == some_system_call ();
}

IMO, bool is an overrated type, perhaps a carry over from other languages. int works just fine as a boolean type.

Crossbreed answered 12/2, 2010 at 18:23 Comment(7)
Re "overrated": In C++, bool is a separate type so it can participate in function overloading, for much of the same reason why character constants are of type char in C++. Of course, this doesn't apply in C, which has no function overloading.Shawanda
No, C is broken in that it doesn't distinguish between boolean and integer.Hoye
C is hardly broken. An integer is a set of booleans which may be manipulated in parallel. Evaluating the set as a whole is their ORed value.Crossbreed
@starblue: C99 introduced a dedicated boolean type; if it eases your mind, you can pretend that C automatically converts scalar values to _Bool in boolean contexts, a feature found in many dynamic languages as wellChlorophyll
The nice thing about _Bool is that it allows the compiler to store it in whatever way works best (a byte, a word, a bit, whatever); maybe even giving you the option of determining its size at compile time (like in some compilers, where you can specify an int as 2 or 4 bytes, or a long as 4 or 8 bytes). Have a processor that wants to access things as words? Make _Bool the word size. Does your processor access bytes as easily as words? Make it a byte to save space. Got bit-access instructions? Maybe, maybe not. Continuing C's long tradition of not nailing down int sizes...Dripping
I can live with the way C works, but I think it was a design mistake not to cleanly separate boolean and integer types. C++ tries to rectify that, but is hindered by the need for backward compatibility with C. That the same mistake is made in other languages doesn't make it any better.Hoye
@Hoye Would not call it a mistake. It made complete sense in the 70:ths.Cheapskate
C
4

You can test if bool is defined in C99's stdbool.h with

#ifndef __bool_true_false_are_defined || __bool_true_false_are_defined == 0
//typedef or define here
#endif
Crabbe answered 12/2, 2010 at 18:24 Comment(1)
Sorry about my last comment, my PDF search facility is broken. See section 7.16 for more info on __bool_true_false_are_defined.Shawanda
S
2

I would go for 1. I haven't met incompatibility with it and is more natural. But, I think that it is a part of C++ not C standard. I think that with dirty hacking with defines or your third option - won't gain any performance, but only pain maintaining the code.

Seineetmarne answered 12/2, 2010 at 18:17 Comment(3)
bool is part of C++, but _Bool (with bool as an alias) is now part of C (as of C99).Blanchette
I would not go for 1, as any non-zero value is true. So with signed quantities, -1 is also true.Colleague
I mean option 1 ... with bool typeSeineetmarne
T
2

I used to use the #define because they make code easier to read, and there should be no performances degradation compared to using numbers (0,1) coz' the preprocessor converts the #define into numbers before compilation. Once the application is run preprocessor does not come into the way again because the code is already compiled.

BTW it should be:

#define FALSE 0 
#define TRUE 1

and remember that -1, -2, ... 2, 3, etc. all evaluates to true.

Turpitude answered 12/2, 2010 at 18:20 Comment(3)
TRUE is a write-only value -- when reading/comparing, etc., any non-zero value needs to be treated as true.Blanchette
for some reason TRUE seems to commonly be defined as #define TRUE !(FALSE)Egocentrism
@Egocentrism - That's because !1 returns 0, but !0 returns a true value, which could be a wide variety of numbers. #define TRUE !(FALSE) makes sure that TRUE == !0 regardless of what exact value !0 returns.Unreliable
C
2

I prefer (1) when I define a variable, but in expressions I never compare against true and false. Just take the implicit C definition of if(flag) or if(!flag) or if(ptr). That’s the C way to do things.

Cockrell answered 12/2, 2010 at 18:22 Comment(0)
C
2

I don't know you specific situation. Back when I was writing C programs, we have always used #2.

#define FALSE = 0
#define TRUE = !FALSE

This might be otherwise under alien platform to DOS or Intel-based processors. But I used to use both C and ASM together writing graphic libraries and graphical IDE. I was a true fan of Micheal Abrash and was intending to learn about texture mapping and so. Anyway! That's not the subject of the question here!

This was the most commonly used form to define boolean values in C, as this headerfile stdbool.h did not exist then.

Clam answered 12/2, 2010 at 18:50 Comment(3)
you might want to do this #define TRUE = (!(FALSE))Trakas
What's the benefit over #define TRUE = 1?Jochebed
First, don't put the equal sign (=) in a #define. Second, only FALSE has a defined value; zero. TRUE is any other value.Regulator
Z
1

There is no real speed difference. They are really all the same to the compiler. The difference is with the human beings trying to use and read your code.

For me that makes bool, true, and false the best choice in C++ code. In C code, there are some compilers around that don't support bool (I often have to work with old systems), so I might go with the defines in some circumstances.

Zendavesta answered 12/2, 2010 at 18:51 Comment(0)
A
1

1 is most readable not compatible with all compilers.

No ISO C compiler has a built in type called bool. ISO C99 compilers have a type _Bool, and a header which typedef's bool. So compatability is simply a case of providing your own header if the compiler is not C99 compliant (VC++ for example).

Of course a simpler approach is to compile your C code as C++.

Accordingly answered 12/2, 2010 at 19:47 Comment(5)
Any C code of sufficient complexity will not compile with a C++ compiler. If you want to use a C++ compiler, then code C++.Cheapskate
@Broman I don't think complexity has much to do with it; rather subtle semantic differences. C++'s stronger type checking will issue issue diagnostic that C compilation does not. For the most part it is possible to resolve such issues and for the code to be both valid and semantically identical in both languages, and most often the result will be better code in any case. But it is true that a large (rather than necessarily complex) C code base is unlikely to compile un-modified.Accordingly
True that it's not strictly about complexity. What I meant was that most non-trivial programs will include a malloc call, and then you need to cast. If you're going to compile it with a C++ compiler, why not just code C++ instead?Cheapskate
@Broman If you compile it as C++, it is C++, even if it is also valid C. The use of malloc() and the need to cast is one instance where making the C code C++ compilable results in marginally worse C code.Accordingly
@Broman Moreover, it is a very old answer. VC++ has much more comprehensive C99 support by now, including stdbool.h. The C++ aside really only applied if you were stuck with C90, which is increasingly unlikely.Accordingly
B
0

I prefer the third solution, i.e. using 1 and 0, because it is particularly useful when you have to test if a condition is true or false: you can simply use a variable for the if argument.
If you use other methods, I think that, to be consistent with the rest of the code, I should use a test like this:

if (variable == TRUE)
{
   ...
}

instead of:

if (variable)
{
   ...
}
Bystreet answered 12/2, 2010 at 21:13 Comment(1)
It's bad to test against TRUE, in C. See my comment above.Regulator
S
0

I prefer to use

#define FALSE (0!=0) 
#define TRUE  (0==0)

or directly in the code

if (flag == (0==0)) { ... }

The compiler will take care of that. I use a lot of languages and having to remember that FALSE is 0 bothers me a lot; but if I have to, I usually think about that string loop

do { ... } while (*ptr);

and that leads me to see that FALSE is 0

Slacks answered 24/4, 2019 at 11:36 Comment(0)
S
0

Adopt a coding style consistent with your current project; if this is not applicable, default to the style used in a project you highly respect or admire:

Linux kernel coding style

  1. Using bool

The Linux kernel bool type is an alias for the C99 _Bool type.

Seto answered 17/12, 2023 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.