BM Balmiki Mandal 27 Dec 2022 4 views 0 comments C Programming

Write a program for conditional compilation using macros

How to Write a C Program for Conditional Compilation Using Macros

Conditional compilation in C allows for certain sections of code to be compiled only under certain conditions. This is typically accomplished using preprocessor macros. Here's an example program that demonstrates how to use conditional compilation in C using macros:

#include <stdio.h>

#define OPTION_A 1
#define OPTION_B 2
#define OPTION_C 3

#define SELECTED_OPTION OPTION_B

int main() {
  #if SELECTED_OPTION == OPTION_A
    printf("Option A selected.\n");
  #elif SELECTED_OPTION == OPTION_B
    printf("Option B selected.\n");
  #elif SELECTED_OPTION == OPTION_C
    printf("Option C selected.\n");
  #else
    printf("Invalid option selected.\n");
  #endif

  return 0;
}

 

Attention: In this program, we define three macros OPTION_A, OPTION_B, and OPTION_C that represent different options. We also define a macro SELECTED_OPTION that specifies which option is selected.

We then use the #if preprocessor directive to conditionally compile code based on the value of SELECTED_OPTION. In this example, the code inside the #elif block corresponding to OPTION_B will be compiled, since SELECTED_OPTION is defined to be OPTION_B.

Note that the #elif and #else blocks are optional, and we can also use #ifdef to test whether a macro has been defined:

#define MY_MACRO 1

#ifdef MY_MACRO
  printf("MY_MACRO is defined.\n");
#else
  printf("MY_MACRO is not defined.\n");
#endif

In this case, the #ifdef directive tests whether the macro MY_MACRO has been defined, and prints a message accordingly.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Bit wise operators Assignment

Bitwise Operators practical assignment: Take runtime input, bit-level manipulation, and different data units r...

AG Anvesh G 27 Sep 2026
Understanding Float and Double Binary Representation in C

Understanding Float and Double Binary Representation in CIntroduction:When we store decimal numbers such as 10...

AG Anvesh G 31 May 2026
Topic-wise C Programming Interview Questions

C Programming Interview Questions – Topic Wise1. IntroductionC programming is one of the most important langu...

AG Anvesh G 30 May 2026