Label can only be used as part of a statement Error

前端 未结 2 2124
青春惊慌失措
青春惊慌失措 2021-02-19 11:01

I have been looking through the forums but I have not found an answer to this question that applies to my situation. I am trying to make a system call to using \'sort\' (unix),

相关标签:
2条回答
  • 2021-02-19 11:45

    When define a variable below a label, you shall tell the scope of the variable(using brace).

    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.");
    }
    
    0 讨论(0)
  • 2021-02-19 11:51

    In C (opposite to C++) declarations are not statements. Labels may precede only statements. You can write for example inserting a null statement after the label

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

    Or you can enclose the code in braces

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

    Take into account that in the first case the scope of the variable is the switch statement while in the second case the scope of the variable is the inner code block under the label. The variable has automatic storage duration. So it will not be alive after exiting the corresponding code blocks.

    0 讨论(0)
提交回复
热议问题