What is the #ifndef directive in C?

The #ifndef directive is one of the widely used 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 any subsequent code is included.

Syntax

#ifndef `macro_definition`

// macro_definition must not be defined if the preprocessor wants to include the source code during compilation. 

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

Code

Example of the use of #ifndef in C:

#include <stdio.h>
// we define a variable
#define xyz 32
int main()
{
// now we use #ifndef to see if xyz is defined or not
// in this example, it is defined, we ll move to the
// #else part of the code.
#ifndef xyz
printf("Error printing lottery number");
#else
printf("Your lottery number is %d", xyz);
#endif
return 0;
}

The output:

Your lottery number is 32

Now let’s remove the #define xyz 32 statement in the code:

#include <stdio.h>
int main()
{
// now we use #ifndef to see if xyz is defined or not
// in this example, it is not defined, we ll move to the
// #ifndef execution of the code.
#ifndef xyz
printf("Error printing lottery number");
#else
printf("Your lottery number is %d", xyz);
#endif
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved