在if语句中声明数组

时间:2013-08-01 14:42:56

标签: c arrays 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”。

5 个答案:

答案 0 :(得分:4)

喜欢:

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

否则你必须使用strcpy()并在if:

之前声明数组
 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 

答案 1 :(得分:2)

您的代码转换为

#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()返回一些内容。

答案 2 :(得分:2)

请改用:

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

printf("%s",y);

通过在y语句之前声明if而不在内部,您正在扩展y范围。你不需要括号。


编辑:(来自Eric和Carl的评论)

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 可以是或包含声明

所以这里的声明完全是非法的。您无法在没有大括号的y中声明if-statement

但是如果你添加大括号:

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

printf("%s",y); 

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

答案 3 :(得分:-1)

如果范围不在main函数中,则表示数组声明。因此您无法访问它们。在main函数的开头声明它。这对数组来说并不特别。从技术上讲,在C89中,所有变量都是在作用域的开头定义的,C ++允许在作用域的任何地方声明变量。 (感谢larsmans的评论。我认为应该更新许多教科书和博客文章。)

答案 4 :(得分:-1)

如果我加入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();
   }

这能解释发生了什么吗?

相关问题