标签只能作为语句的一部分使用 Error

Label can only be used as part of a statement Error

我一直在浏览论坛,但没有找到适用于我的情况的这个问题的答案。我正在尝试使用 'sort' (unix) 进行系统调用,但是,我收到一条错误消息,说 "a label can only be part of a statement and a declaration is not a statement." 这是导致错误的代码。

int processid;  
switch(processid = fork()){                 //establishing switch statement for forking of processes.
case -1:
    perror("fork()");
    exit(EXIT_FAILURE);
    break;
case 0:
    char *const parmList[] = {"usr/bin/sort","output.txt","-o","output.txt",NULL};  //execv call to sort file for names.
    break;
default:
    sleep(1);
    printf("\nChild process has finished.");
}

在系统调用中,我试图按字母顺序对文件进行排序,以便按名称简单地收集相似的术语。

我很傻眼,因为这个错误发生在一个 char * const 中,其中包含我的 execv 系统调用的命令。此 EXACT switch 语句适用于不同的程序文件。有人可以发现我缺少的东西吗? 谢谢

在 C(与 C++ 相反)中,声明不是语句。标签只能位于语句之前。您可以编写例如在标签

之后插入空语句
case 0:
    ;
    char *const parmList[] = {"usr/bin/sort","output.txt","-o","output.txt",NULL};  //execv call to sort file for names.
    break;

或者您可以将代码括在大括号中

case 0:
    {
    char *const parmList[] = {"usr/bin/sort","output.txt","-o","output.txt",NULL};  //execv call to sort file for names.
    break;
    }

请注意,在第一种情况下,变量的范围是switch语句,而在第二种情况下,变量的范围是标签下的内部代码块。该变量具有自动存储期限。所以退出对应的代码块后就不会存活了。

在label下面定义变量时,要说明变量的作用域(用大括号)。

int processid;
switch(processid = fork())
{                 //establishing switch statement for forking of processes.
    case -1:
        perror("fork()");
        exit(0);
        break;
    case 0:
    {
        char *const parmList[] = {"usr/bin/sort","output.txt","-o","output.txt",NULL};  //execv call to sort file for names.
        break;
    }
    default:
        sleep(1);
        printf("\nChild process has finished.");
}