3

As C does not have boolean types, how can I write a function like this in C:

bool checkNumber()
{
   return false;
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
olidev
  • 20,058
  • 51
  • 133
  • 197

4 Answers4

17

The bool type is defined in the <stdbool.h> header, and is available under the name _Bool otherwise (assuming you're using a C99 compiler). If you don't have C99, you can always invent your own bool type like this:

typedef enum {false, true} bool;
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
9

int is commonly used as a Boolean in C, at least prior to C99. Zero means false, non-zero means true.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
1

You could use defines to avoid using ints and 1s and 0s directly for boolean logic.

#define BOOL char
#define TRUE 1
#define FALSE 0

I chose char for BOOL because it's only 1 byte instead of 4. (For most systems)

jonescb
  • 22,013
  • 7
  • 46
  • 42
  • 1
    It's better to do this kind of thing with an enum rather than relying on the pre-processor - it's more robust and it's better for debugging (you get symbols rather than literal constants) - see @templatetypedef's answer. – Paul R Jan 20 '11 at 22:04
  • 3
    This kind of nonsense typically leads to code like `if (var == TRUE)`. Either use C99 `_Bool` with boolean semantics, or use an `int` and don't write any equality expressions but instead simply `if (var)` and `if (!var)`. – R.. GitHub STOP HELPING ICE Jan 20 '11 at 22:09
  • Another problem with this is that just about every third-party library header you might ever use casually defines similar or identical macro identifiers (including for example windows.h) to these. – Clifford Jan 20 '11 at 23:03
1

If you are not using C99, and determine that you need to add your own boolean type, then ensure that you give it its own name. Using 'bool' or 'BOOL' will only get you into trouble when you include a 3rd party library. The only exception would be to use the de-facto standard of:

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

But ensure you wrap these in #ifndef. But note that some libraries do use 'char' as BOOL. If you are coming from C++ background, have a think as to whether you will want to interoperate with C++.

Keith
  • 6,756
  • 19
  • 23