Home > Software engineering >  Why to use a const int and not a #define when declaring true and false
Why to use a const int and not a #define when declaring true and false

Time:07-11

I am starting with C and OpenGL and came across the situation where I wanted to have true and false as boolean values, but couldn't get them, since they don't exist as such in C. I then came up with the idea to use the #define to just define them in a utils.h I use in almost all other files anyways, but wanted to check if that is okay with the standards or if there is some reason one shouln't do that. I then came across a site, which made it clear, that this is ok for convenience, but had a little section which left me confused:

To make life easier, C Programmers typically define the terms "true" and "false" to 
have values 1 and 0 respectively.

In the old days, this was done using #define:
    #define true 1
    #define false 0
Today it is better to use const int instead of #define:
    const int true = 1;
    const int false = 0;

Is that true, and if so, why is that better?

Eventually I just went with stdbool.h, as described there, but the other thing really left me puzzled.

CodePudding user response:

The upside of making them const int is that they are proper variables and you can't make mistakes when defining and using them as easily which is often the case with #defines.

But, I wouldn't say it's better to make them const int since they then couldn't be used where compile-time constant expressions are needed. I would have suggested:

enum { false, true };

That would give you the same upside as making them const int (they are in fact const int but compile-time constants) - but they would also be usable in situations where you need a compile-time constant expression.

  • Related