What is difference between #if and #ifdef ?

Answer: Difference between #if and #ifdef Preprocessor Directives is as below in C, C++. lets understand the both #if and #ifdef by example and use.

#ifdef:

This Preprocessor Directives #ifdef only checks if the symbol is defined or not and doesn’t care for its value.
For example, symbol LOG_ENABLED has been defined here and has a value 0 or 1.
#define LOG_ENABLED 0 // YES =1, NO=0
So, Below statement only checks if the symbol is defined and not it’s value, and all the code in this section will be enabled if it is defined.

#ifdef LOG_ENABLED //
// codes
#endif

Other examples can be like this
#ifdef _DEBUG
# endif

#ifdef _WIN32
# endif

 

#if :

#if checks the value of the symbol. For example,#if LOG_ENABLED preprocessor directive will check its value if it 0 or 1 or anything what we have defined for this symbol.

So,All code within below section will be enabled or disabled depending upon symbol value. If compiler finds its value 0, all code will disabled or else enabled.
#if LOG_ENABLED
//code
#endif

Complete Example:

#define LOG_ENABLED 0 // YES =1, NO=0

int main()
{

#ifdef LOG_ENABLED
	// all code will compile under this section
	//as #ifdef checks if symbol(LOG_ENABLED) exist or not 
	printf("#ifdef Section \n");
#endif


#if LOG_ENABLED
	// This section will not be compiled if value of macro
	//LOG_ENABLED is 0

	printf("#ifdef Section \n");
#endif

	return 0;
}

NOTE

:We frequently use #if preprocessor directive for enabling and disabling code for debuging purpose in functions or any section of program.

#if 0

//All code disabled within this

#endif

#if 1

//All code enabled within this

#endif

Related Posts