Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is TRUE/FALSE part of C standard?

Tags:

c

TRUE/FALSE is usually defined in C as below. Are these definitions part of C standard which is supported by varies compiler implementations?

#define TRUE 1
#define FALSE 0
like image 710
Thomson Avatar asked Sep 20 '25 03:09

Thomson


2 Answers

No for TRUE or FALSE. Yes for true and false in C99 or later if you include <stdbool.h>.

like image 127
T.C. Avatar answered Sep 22 '25 19:09

T.C.


C99 and C11 define an integral type with Boolean semantics called _Bool, but no actual true/false keywords exist.

The _Bool type is only capable of storing the values 1 and 0. Any value that doesn't compare equal to 0 is converted to 1, and any value comparing equal to 0 is converted to 0.

By including <stdbool.h>, the _Bool type is allowed to be written as bool as with some other languages, and true and false C preprocessor macros are defined to be 1 and 0 respectively.

Before that, it was somewhat of a convenience for someone to define constants like

#define TRUE 1
#define FALSE 0
typedef char BOOL; /* or #define BOOL char */

or sometimes

typedef enum {False, True} BOOL;

Unlike C99, however, both have at least one flaw:

BOOL bClicked = False;

++bClicked, ++bClicked;

if (bClicked == False)
    printf ("False\n");
else if (bClicked == True)
    printf ("True\n");
else
    printf ("Unknown: %d\n", bClicked);

That will print "Unknown: 2" because the defined BOOL type isn't a true Boolean type.

The C99 version:

_Bool bClicked = 0;

++bClicked, ++bClicked;

if (bClicked == 0)
  printf ("False\n");
else if (bClicked == 1)
  printf ("True\n");
else
  printf ("Unknown: %d\n", bClicked);

That will print "True" because _Bool can only store 0 and 1, so incrementing 1 to get 2, which compares as not equal to 0, results in 1.

Of course, most people just use the language to their advantage rather than actually comparing against True/False constants:

if (bClicked)
  {
    /* True if bClicked does not compare equal to 0 */
  }
else
  {
    /* False */
  }

Because of that behavior, there isn't any real need for a Boolean type or true/false constants; they exist purely for indication of intent.

I vaguely remember someone ranting that some Windows API functions return a value of type BOOL, but TRUE and FALSE weren't the only possible return values, so despite returning a value that should have been a simple comparison as in that last bit of code, more comparisons were needed to handle all possible cases. Had there been an actual Boolean type back then, most likely those functions, whatever they are/were would have returned a value of type int instead. A BOOL return type suggests only two values can be returned, but apparently that wasn't the case with those functions, perhaps because there was a third (error) return value.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!