Search code examples
cmacros

understanding C macros when they are inside some conditional statements like switch/if/esle


As you can see from the code that i have a switch statement and here inside each separate switch branch I'm defining a macro. and in later part of the code, based upon these macros I'm printing some ouput to terminal. So in this scenario what would be the output of the below code?

    #include <stdio.h>
    int main() 
    {
        // k integer to hold user input
        int k;
        
        scanf("%d",&k); // capture input here

        switch(k)
        {
            case 1 :
            #define first_case
            break;
            case 2 :
             #define second_case
            break;
            case 3 :    
             #define third_case
            break;
            case 4 : 
            #define fourth_case
            break;
        }
        
    
 #ifdef first_case
        printf(" first_case\n");
  #endif

  #ifdef second_case
        printf(" second_case\n");
  #endif
        
  #ifdef third_case
        printf(" third_case\n");
 #endif

   #ifdef fourth_case
        printf(" fourth_case\n");
 #endif
    
    }


Solution

  • Macros (#define MACRO ...) are processed by the C preprocessor before the actuel compile process takes place.

    So the compiler only "sees" this once the file has been preprocessed:

    int main()
    {
      // your code goes here
      int k = 0;
    
      scanf("%d", &k);
      switch (k)
      {
      case 1:
        break;
      case 2:
        break;
      case 3:
        break;
      case 4:
        break;
      }
    
      printf("typed first_case\n");
      printf("typed second_case\n");
      printf("typed third_case\n");
      printf("typed fourth_case\n");
    }
    

    You could write your program like this, and the outcome would be exactly the same:

    #define first_case
    #define second_case
    #define third_case
    #define fourth_case
    
    /* Find the longest line among the giving inputs and print it */
    
    #include <stdio.h>
    int main()
    {
      // your code goes here
      int k = 0;
    
      scanf("%d", &k);
      switch (k)
      {
      case 1:
        printf("case 1\n");
        break;
      case 2:
        break;
      case 3:
        break;
      case 4:
        break;
      }
    
    
    #ifdef first_case
      printf("typed first_case\n");
    #endif
    #ifdef second_case
      printf("typed second_case\n");
    #endif
    
    #ifdef third_case
      printf("typed third_case\n");
    #endif
    #ifdef fourth_case
      printf("typed fourth_case\n");
    #endif
    
    }