Showing posts with label C #if. Show all posts
Showing posts with label C #if. Show all posts

Thursday, July 12, 2018

C #if

Description

In the C Programming Language, the #if directive allows for conditional compilation. The preprocessor evaluates an expression provided with the #if directive to determine if the subsequent code should be included in the compilation process.

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:





#if expression
//code
#endif



Syntax with #else:



#if expression
//if code
#else
//else code
#endif



Syntax with #elif and #else:



#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif



Note

  • The #if directive must be closed by an #endif directive.

C #if example

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





#include <stdio.h>
#include <conio.h>
#define NUMBER 0
void main() {
#if (NUMBER==0)
printf("Value of Number is: %d",NUMBER);
#endif
getch();
}



Output:

Value of Number is: 0

Let's see another example to understand the #if directive clearly.





#include <stdio.h>
#include <conio.h>
#define NUMBER 1
void main() {
clrscr();
#if (NUMBER==0)
printf("1 Value of Number is: %d",NUMBER);
#endif

#if (NUMBER==1)
printf("2 Value of Number is: %d",NUMBER);
#endif
getch();
}



Output:

2 Value of Number is: 1

Example

The following example shows how to use the #if directive in the C language:





/* Example using #if directive */

#include <stdio.h>

#define WINDOWS 1

int main()
{
printf("C programming is a great ");

#if WINDOWS
printf("Windows ");
#endif

printf("resource.\n");

return 0;
}



Here is the output of the executable program:

C programming is a great Windows resource.




Instagram