The defined() operator
What you'll learn: How to check if a macro exists using the defined() operator to make your conditional compilation logic cleaner and more flexible.
Checking for existence
In previous lessons, we used #ifdef to check if a macro was created. While #ifdef works for simple checks, it is a bit of a "one-trick pony." Imagine you are building a game that needs to run on Windows, macOS, and Linux. If you want to run a specific piece of code only if the OS is either Windows or macOS, #ifdef can’t help you in a single line. You would have to nest multiple statements, which gets messy fast.
The defined() operator is a more powerful tool that lives inside an #if or #elif statement. It asks a simple true/false question: "Does this macro exist?" If the macro has been defined (even if it has no value), the operator results in 1 (true); otherwise, it is 0 (false).
Why use it?
Think of defined() like a sensor. Instead of just checking one thing, you can combine multiple sensors using logical operators like && (AND), || (OR), and ! (NOT).
Common use cases include:
- Feature Toggles: Enabling code only if multiple conditions are met.
- Platform Compatibility: Writing code that works for "Anything except Linux."
- Debug Modes: Running specific logs only when
DEBUGis on andVERBOSEis also enabled.
Example: Combining conditions
In the code below, we use defined() to check for multiple platform macros at once. This keeps our code readable and prevents "indentation hell."
#include <stdio.h>
// Imagine these are defined by your compiler or build system
#define WINDOWS
#define VERSION_2
int main() {
// Using '||' to check if either macro exists
#if defined(WINDOWS) || defined(MACOS)
printf("Running on a desktop OS.\n");
#endif
// Using '&&' and '!' to check for complex logic
#if defined(VERSION_2) && !defined(LEGACY_MODE)
printf("Modern features enabled.\n");
#endif
return 0;
}
By using defined(), you treat macro existence just like any other boolean logic. It makes your preprocessor directives look and feel much more like standard C code, allowing for sophisticated control over which lines of code actually make it to the compiler.
Key takeaway
The defined() operator allows you to combine multiple macro existence checks into a single #if statement using logical operators like AND, OR, and NOT.