ADVERTISEMENT

What are #ifndef and #define Directives

#ifndef and #define
ADVERTISEMENT

In the C Programming Language, the #ifndef directive checks if the given token has been #defined earlier in the C code. If the token has not been defined earlier then it includes the code between #ifndef and #else. If no #else is present then code between #ifndef and #endif is included.

The both #ifndef and #define directives are known as header guards or #include guard in C/C++. They are used to prevent multiple declarations of variables and other data types and header files from being included multiple times. The #ifndef also prevents recursive inclusions of header files. Another non-standard preprocessor directive named #pragma once is widely used to force the inclusion of a header file only once.

The syntax of using #ifndef is as below:

#ifndef 
#define 
// some code declarations
#endif

Use of #ifndef and #define

Here is a rather complete C program to demonstrate the use of #ifndef and #define.

#include <stdio.h>

#ifndef INTEREST_RATE
#define INTEREST_RATE 8
#endif

int main()
{
   printf("Current Interest Rate is %d percent.\n", INTEREST_RATE );

   return 0;
}

The output of the above C program is:

Current Interest Rate is 8 percent.

Here is a another C program to demonstrate the use of #ifndef and #define. As INTEREST_RATE is already defined so #ifndef does not execute.

#include <stdio.h>

#define INTEREST_RATE 9
#ifndef INTEREST_RATE
#define INTEREST_RATE 8
#endif

int main()
{
   printf("Current Interest Rate is %d percent.\n", INTEREST_RATE );

   return 0;
}

The output of the above program is:

Current Interest Rate is 9 percent.
ADVERTISEMENT
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post