C language #ifdef, #else, #endif Pre-processor with Example

#ifdef, #else, #endif

The directives #ifdef, #else and #endif are logical pre-processor directives which are used to specify which code will be compiled through the compiler based on defined macros.

Let suppose if you have two code segments and want to compile only one code segment according to current requirement and other one want to compile later based on different requirement, in such case we use these pre-processor directives.

Let's consider the following example

#include <stdio.h>

#define DEBUG 1

int main(){
	#ifdef DEBUG
		printf("Debug is ON\n");
		printf("Hi friends!\n");
	#else
		printf("Debug is OFF\n");
	#endif
	return 0;
}

Output

Debug is ON 
Hi friends!

In this example macro DEBUG is defined so code written within the #ifdef and #else will be executed.

If macro DEBUG was not defined, code written within the #else and #endif will be executed.

Now, remove the defined macro DEBUG

Let's consider the following example

#include <stdio.h>

//#define DEBUG 0

int main(){
	#ifdef DEBUG
		printf("Debug is ON\n");
		printf("Hi friends!\n");
	#else
		printf("Debug is OFF\n");
	#endif
	return 0;
}

Output

Debug is OFF

These pre-processor directives are much similar to if else statement, this conditional compilation works at compile time and check macros. While if else statements check two operands (variables or/and values) and executes at run time.





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.