Quick links: C-Tricks HR Interview Que. Code Snippets C Programs C++ Programs Java Programs PHP Examples

Home » C programming language

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!

Sponsored Links



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

Solved programs


Sponsored Links


Most viewed pages


Featured posts
C Tips and Tricks

Keywords (like Linux, Java, Oracle etc) used in this website are the trademarks of their respective owners/company. This website is not affiliated to any company. The tutorials are designed by includehelp Team with the help of well known books and other online resources. These Tutorials are free for all, for learning purposes only. Enjoy learning:)
Copyright © 2015 - 2016. All Rights Reserved.