← Back to C Course | Chapter 11: Preprocessor | Lesson 4 of 5

C Conditional Compilation

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

c
#include <stdio.h>
#define DEBUG
int main() {
	#ifdef DEBUG
	printf("Debug info enabled");
	#endif
	return 0;
}

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

c
#ifndef MY_HEADER_H
#define MY_HEADER_H
#include <stdio.h>
int main() {
	printf("Guarded content");
	return 0;
}
#endif

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

c
#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;
}

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

c
#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;
}

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

c
#ifndef POINT_H
#define POINT_H
#include <stdio.h>
int main() {
	printf("Standard three-directive guard pattern");
	return 0;
}
#endif
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.