C #ifdef

Description

In the C Programming Language, the #ifdef directive allows for conditional compilation. The preprocessor determines if the provided macro exists before including the subsequent code in the compilation process.

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:




#ifdef MACRO  
//code  
#endif  



Syntax with #else:




#ifdef MACRO  
//successful code  
#else  
//else code  
#endif 



C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.




#include <stdio.h>
#include <conio.h>
#define NOINPUT  
void main() {  
int a=0;  
#ifdef NOINPUT  
a=2;  
#else  
printf("Enter a:");  
scanf("%d", &a);  
#endif         
printf("Value of a: %d\n", a);  
getch();  
}  



Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.




#include <stdio.h>
#include <conio.h>
void main() {  
int a=0;  
#ifdef NOINPUT  
a=2;  
#else  
printf("Enter a:");  
scanf("%d", &a);  
#endif         
  
printf("Value of a: %d\n", a);  
getch();  
}  



Output:

Enter a:5

Value of a: 5

Example

The following example shows how to use the #ifdef directive in the C language:




/* Example using #ifdef directive by C programming*/

#include <stdio.h>

#define YEARS_OLD 10

int main()
{
   #ifdef YEARS_OLD
   printf("C programming is over %d years old.\n", YEARS_OLD);
   #endif

   printf("C programming is a great resource.\n");

   return 0;
}



Here is the output of the executable program:

C programming is over 10 years old.

C programming is a great resource.

A common use for the #ifdef directive is to enable the insertion of platform specific source code into a program.

The following is an example of this:




/* Example using #ifdef directive for inserting platform 
 * specific source code by C programming*/

#include <stdio.h>

#define UNIX 1

int main()
{
   #ifdef UNIX
   printf("UNIX specific function calls go here.\n");
   #endif

   printf("C programming is over 10 years old.\n");

   return 0;
}



The output of this program is:

UNIX specific function calls go here.

C programming is over 10 years old.

In this example, the UNIX source code is enabled. To disable the UNIX source code, change the line #define UNIX 1 to #define UNIX 0.




Instagram