All for Joomla All for Webmasters

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO
  2. //code
  3. #endif

Syntax with #else:

  1. #ifdef MACRO
  2. //successful code
  3. #else
  4. //else code
  5. #endif

C #ifdef example

Let’s see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>
  2. #include <conio.h>
  3. #define NOINPUT
  4. void main() {
  5. int a=0;
  6. #ifdef NOINPUT
  7. a=2;
  8. #else
  9. printf(“Enter a:”);
  10. scanf(“%d”, &a);
  11. #endif       
  12. printf(“Value of a: %d\n”, a);
  13. getch();
  14. }

Output:

Value of a: 2

But, if you don’t define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>
  2. #include <conio.h>
  3. void main() {
  4. int a=0;
  5. #ifdef NOINPUT
  6. a=2;
  7. #else
  8. printf(“Enter a:”);
  9. scanf(“%d”, &a);
  10. #endif       
  11. printf(“Value of a: %d\n”, a);
  12. getch();
  13. }

Output:

Enter a:5
Value of a: 5
PinIt
submit to reddit

Leave a Reply

Top