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!

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.






Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.