繁体   English   中英

在if语句中声明数组

[英]Declaring arrays inside an if statement

#include <stdio.h>

int main(){
    char x;

    printf("enter something ");
    scanf("%c",&x);

    if(x == 's') char y[] = "sauve";

    else char y[] = "hi"

    printf("%s",y);
    getch();
}

它说不是先声明“ y”。 我是数组的新手。 我想做的是当用户输入字母s时显示字符串“ suave”。

喜欢:

 char *y;
 if(x == 's') y = "sauve";
 else y = "hi";
 printf("%s",y);

否则,您必须在以下情况下使用strcpy()并声明数组:

 char y[SIZE] = "";       //1. sufficiently long size
 if(x == 's') 
      strcpy(y, "sauve"); //2. after declaration you can't assign used strcpy
 else 
     strcpy(y, "hi");
 printf("%s", y);        //3. now scope is not problem 

您的代码转换为

#include<stdio.h>
int main() {
    char x;
    printf("enter something ");
    scanf("%c",&x);
    if(x == 's') {
        char y[] = "sauve";
    } else {
        char y[] = "hi";
    }
    printf("%s",y);
    getch();
}

现在看来似乎更显而易见的是,您声明的变量y绑定到了声明的{...}范围。您不能在声明其的范围之外使用y。要解决此问题,请声明在外部范围中的“ y”是这样的:

#include<stdio.h>
int main() {
    char x;
    printf("enter something ");
    scanf("%c",&x);
    const char *y;
    if(x == 's') {
        y = "sauve";
    } else {
        y = "hi";
    }
    printf("%s",y);
    getch();
    return 0;
}

还要注意我如何使用指针而不是数组,因为定义“ y”时无法知道数组的大小。 同样不要忘记从main()返回某些内容。

使用它代替:

char *y;
if(x == 's') y = "sauve";
else y = "hi";

printf("%s",y);

通过在if语句之前而不是内部声明y ,可以扩展y范围。 而且您在这里不需要括号。


编辑:(从埃里克和卡尔的评论)

if (x == 's') char y[] = "sauve";
else char y[] = "hi";

printf("%s",y); 

在C语法中, 声明不是语句。 if的语法是if (expression) statement [else statement] 如果不带大括号,则单个“陈述”必须为陈述。 它可能不是声明 它可以是复合语句 ,它是一个用大括号括起来的block-item-list ,而block-item-list可以是或者包含一个声明

因此,这里的声明完全是非法的。 您不能在没有大括号的if-statement声明y

但是,如果您添加大括号:

if (x == 's') { char y[] = "sauve"; }
else { char y[] = "hi"; }

printf("%s",y); 

这在理论上是合法的,但现在有一个新问题…… y的声明现在受{ ... }范围的限制。 将出现以下类型的错误: error: use of undeclared identifier 'y'printf行上error: use of undeclared identifier 'y'

如果范围不在主函数中,则数组声明在其中。 因此,您无法访问它们。 在主要功能的开头声明它。 数组没有什么特别的。 从技术上讲,在C89中,所有变量都在作用域的开始处定义,C ++允许在作用域中的任何位置声明变量。 (感谢拉尔斯曼先生的评论。我认为许多教科书和博客条目都应进行更新。)

如果我把blocks {}放进去,我们得到:

#include<stdio.h>
    int main(){
    char x;

    printf("enter something ");
    scanf("%c",&x);

    if(x == 's') { char y[] = "sauve";}

    else {char y[] = "hi";}

    printf("%s",y); /* y is now out of scope of both its declarations*/
    getch();
   }

这说明发生了什么吗?

暂无
暂无

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

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