C #ifdef

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:

snippet
#ifdef MACRO
//code
#endif

Syntax with #else:

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

C #ifdef example

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

snippet
#include 
#include 
#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:

Output
Value of a: 2

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

snippet
#include 
#include 
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:

Output
Enter a:5 Value of a: 5
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +