在C编程中理解宏的问题

时间:2017-12-07 11:16:31

标签: c macros

如果我给出' 1'以下代码的输出是什么?作为输入,为什么?

FYI :: iam使用gcc构建代码。

#include <stdio.h>
int main() 
{
    // k integer to hold user input
    int k=0;

    scanf("%d",&k);

    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(&#34; first_case \ n&#34;);   #ENDIF

#ifdef second_case         printf(&#34; second_case \ n&#34;);   #ENDIF

#ifdef third_case         printf(&#34; third_case \ n&#34;);  #ENDIF

#ifdef fourth_case         printf(&#34; fourth_case \ n&#34;);  #ENDIF

}

2 个答案:

答案 0 :(得分:1)

在执行编译过程之前,

宏(#define MACRO ...)由C预处理器处理。

因此,一旦文件被预处理,编译器只会“看到”这个:

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");
}

你可以像这样写你的程序,结果将是完全相同的:

#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

}

答案 1 :(得分:1)

正如其他人所说,在运行时无法设置或更改预处理器宏,您只需要一个普通的自动变量。例如:

int k=0;
int first_case = 0;   // 0 resolves to False
int second_case = 0;  // 0 resolves to False
int third_case = 0;   // 0 resolves to False
int fourth_case = 0;  // 0 resolves to False

scanf("%d",&k);
switch(k)
{   
    case 1 :
        printf("case 1\n");
        first_case = 1;
        break;
    case 2 :
        second_case = 1;
        break;
    case 3 :  
        third_case = 1;
        break;
    case 4 :
        fourth_case = 1;
        break;
}

if (first_case)
    printf("typed first_case\n");

if (second_case)
    printf("typed second_case\n");

if (third_case)
    printf("typed third_case\n");

if (fourth_case)
    printf("typed fourth_case\n");

话虽如此,您正在进行两次相同的测试,因此大多数人只会使用case,可能会使用default

scanf("%d",&k);
switch(k)
{   
    case 1 :
        printf("typed first_case\n");
        break;
    case 2 :
        printf("typed second_case\n");
        break;  
    case 3 :    
        printf("typed third_case\n");
        break;
    case 4 : 
        printf("typed fourth_case\n");
        break;
    default :
        fprintf(stderr, "Invalid response: %d\n", k);
}