What is the #ifdef directive in C?

The #ifdef is one of the widely used directives in C. It allows conditional compilations. During the compilation process, the preprocessor is supposed to determine if any provided macrosA macro in computer science is a rule or pattern that specifies how a certain input should be mapped to a replacement output. exist before we include any subsequent code.

widget

Syntax

#ifdef `macro_definition`

macro_definition: We must not define the directive if the preprocessor wants to include the source code during compilation.

The #ifdef directive must always be closed by an #endif directive; otherwise it will cause an error.

Code

Let’s look at an example where we define a macro xyz with the value 10. Now, when we reach line 11, we encounter the #ifdef condition. This statement determines whether or not xyz macro is defined.

For this example, we defined the xyz macro so the #ifdef condition is executed. If xyz were not defined, #else condition would have been executed.

#include <stdio.h>
// define a macro
#define xyz 10
int main()
{
// use conditional if-defined statement
// in this example, xyz is defined so we will execute
// the printf part of #ifdef
#ifdef xyz
printf("Your lottery number is %d.\n", xyz);
#else
printf("error printing lottery number");
#endif
return 0;
}

Now, if you remove the #define xyz 10 statement, this will mean xyz is not defined. The #ifdef fails and printf inside the #ifdef is not executed (see code below):

#include <stdio.h>
int main()
{
// use conditional if-defined statement
// in this example, xyz is not defined so we will not execute
// the printf part of #ifdef, #else is executed.
#ifdef xyz
printf("Your lottery number is %d.\n", xyz);
#else
printf("error printing lottery number");
#endif
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved