CTSD-2 Unit - 3
CTSD-2 Unit - 3
#ifdef MACRO
controlled text
#endif
Conditional Compilation
#ifndef: In #ifdef directive if the macroname is defined, then the block of
statements after the #ifdef directive will be executed normally but in case it is
not defined, the compiler will simply skip this block of statements.
The #ifndef directive is simply the opposite of #ifdef directive.
In case of #ifndef , the block of statements between #ifndef and #endif will
get executed only if the macro or the identifier with #ifndef is not defined.
Syntax
ifndef macro_name
statement1;
statement2;
.
.
statementN;
endif
Conditional Compilation
#if, #else and #elif: All these directives works together and control
compilation of portions of the program using some conditions. If the
condition with the #if directive results in a non zero value, then the group of
line immediately after the #if directive will be executed otherwise if the
condition with the #elif directive evaluates to a non zero value, then the
group of line immediately after the #elif directive will be executed else the
lines after #else directive will be executed.
Conditional Compilation
Syntax
#if macro_condition
statements
#elif macro_condition
statements
#else
statements
#endif
Conditional Compilation
// C program to demonstrate the use of conditional
// directives.
#include <stdio.h>
#define gfg 7
#if gfg > 200
#undef gfg
#define gfg 200
#elif gfg < 50
#undef gfg
#define gfg 50
#else
#undef gfg
#define gfg 100
#endif
Conditional Compilation
void printValue(int value) { printf("%d", value); }
int main()
{
printValue(gfg); // gfg = 50
return 0;
Pragma directive
The #pragma directive is used to provide the compiler some extra
information and hence it is compiler dependent so we can say that it’s
behavior vary according to the compiler we are using. The pragma directive
basically gives the instructions to the compiler to turn on or turn off some
feature and also to give some custom messages required.
Syntax
#pragma directive
Pragma directive
// C program to illustrate the use of Pragma to print the
// custom message
#include <stdio.h>
// not defining gfg to trigger pragma message
// #define GeeksforGeeks
int main()
{
#ifndef GeeksforGeeks
#pragma message(" GfG is not defined.")
#endif
printf("Hello geek!\n");
return 0;
}
Sol. #pragma message: GfG is not defined.
www.paruluniversity.ac.in