C Conditional Compilation
In this page:
Using #ifdef
This is commonly used to include debug-only code, like #ifdef DEBUG ... #endif blocks that print extra diagnostic information, which are compiled out entirely (not just skipped at runtime) in release builds.
Example: Using #ifdef
#include <stdio.h>
#define DEBUG
int main() {
#ifdef DEBUG
printf("Debug info enabled");
#endif
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using #ifndef
This is the core mechanism behind include guards -- a header wraps its own contents in #ifndef HEADER_NAME so the second (and any subsequent) inclusion in the same file sees the guard macro already defined and skips the content entirely.
Example: Using #ifndef
#ifndef MY_HEADER_H
#define MY_HEADER_H
#include <stdio.h>
int main() {
printf("Guarded content");
return 0;
}
#endif
Login to try C/C++/Java/PHP code in the editor
Using #if, #elif, and #else
This mirrors the runtime if/else if/else structure but operates entirely at compile time, evaluating constant expressions (often involving defined() checks) to decide which code path actually gets compiled into the final binary.
Example: Using #if, #elif, and #else
#include <stdio.h>
#define VERSION 2
int main() {
#if VERSION == 1
printf("Version 1");
#elif VERSION == 2
printf("Version 2");
#else
printf("Unknown");
#endif
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using #undef in Logic Flows
This lets you toggle behavior mid-file for testing purposes -- undefining and redefining the same macro at different points changes what subsequent conditional blocks in the same file will include.
Example: Using #undef in Logic Flows
#include <stdio.h>
#define MODE 1
int main() {
#if MODE
printf("Mode active ");
#endif
#undef MODE
#define MODE 0
#if MODE
printf("unreachable");
#else
printf("Mode toggled off");
#endif
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Header Include Guards
The three-directive pattern (#ifndef, #define, #endif) wrapped around an entire header's contents is such a universal convention in C that most editors and IDEs can auto-generate it for you when creating a new header file.
Example: Header Include Guards
#ifndef POINT_H
#define POINT_H
#include <stdio.h>
int main() {
printf("Standard three-directive guard pattern");
return 0;
}
#endif
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: