繁体   English   中英

在 if 语句中定义变量

[英]Defining variables inside if-statement

代码思想是从标准输入中读取单个字符。 如果读取“y”或“n”,程序应分别打印“YES”或“NO.”。

我尝试在if块中使用#define指令:

#include <stdio.h>
#include <stdbool.h>

#define YES y 
#define NO n

int main()
{
    char letter = ' ';
    printf("for Yes enter : y\nfor No enter : n\n");
    letter = getchar();
    if (YES == letter)
    {
        printf("YES!");
    }
    else if (NO == letter)
    {
        printf("NO!");
    }
    else
    {
        printf("this option is not available");
    }
    printf("FUZZY");
    
    getchar();
    return 0;
}

这会导致以下错误:

Ex1.c: In function 'main':
Ex1.c:5:13: error: 'y' undeclared (first use in this function)
 #define YES y
             ^
Ex1.c:13:5: note: in expansion of macro 'YES'
  if(YES == letter)
     ^~~
Ex1.c:5:13: note: each undeclared identifier is reported only once for each function it appears in
 #define YES y
             ^
Ex1.c:13:5: note: in expansion of macro 'YES'
  if(YES == letter)
     ^~~
Ex1.c:6:12: error: 'n' undeclared (first use in this function)
 #define NO n
            ^
Ex1.c:17:10: note: in expansion of macro 'NO'
  else if(NO == letter)

该怎么做才能使此代码正常工作?

“未声明”错误的原因:在预处理阶段之后if语句将变为:

  1. if(YES == letter)更改为if(y == letter)

  2. else if(NO == letter)更改为else if(n == letter)

这两个语句是编译阶段的输入,经过预处理。 显然,没有声明yn变量。 因此,错误。

解决方案:

#define YES 'y' 
#define NO 'n'

在这些更改之后if语句将(在预处理阶段之后):

  1. if(YES == letter)更改为if('y' == letter)

  2. else if(NO == letter)变为else if('n' == letter)

在这里, 'y''n'是字符常量,而不是变量。 因此,您不会收到“未声明”的错误。

首先,您应该删除#include <stdbool.h>

其次,在您的定义中,您将 y 和 x 声明为变量而不是字符,要声明为字符,您应该像这样:'x','y'

#include <stdio.h>
#define YES 'y'
#define NO 'n'

int main()
{
    char letter = ' ';
    printf("for Yes enter : y\nfor No enter : n\n");
    letter = getchar();
    if(YES == letter)
    {
        printf("YES!");
    }
    else if(NO == letter)
    {
        printf("NO!");
    }
    else
    {
       printf("this option is not available");
    }
    printf("\nFUZZY");
    getchar();
    return 0;
}

你应该把 y 和 n 当作字符 'y' 和 'n'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM