我的switch语句出了什么问题?

时间:2014-11-19 00:44:35

标签: c compiler-errors switch-statement

我有这段代码给我带来了一些麻烦:

switch(errorNum){
case 404:

    //Send back a 404 error
    char outputBuf[MAXREQUESTLENGTH];
    int outputLength = sprintf(outputBuf, "%s/r/n/r/n%s/r/n", "HTTP/1.0 404 Not Found","<html><body><h1>404 Page Not Found</h1></body></html>");
    char output[outputLength + 1];
    if(strcpy(output, outputBuf) == NULL){
    die("strcpy error");
    }
    if(send(socketFD, output, outputLength, 0) != outputLength){
    die("send error");
    }       
    break;

当我用这段代码编译我的程序时,我收到了这些错误,

http-server.c: In function 'returnError':
http-server.c:28:6: error: a label can only be part of a statement and a declaration is not a statement
http-server.c:29:6: error: expected expression before 'int'
http-server.c:30:18: error: 'outputLength' undeclared (first use in this function)
http-server.c:30:18: note: each undeclared identifier is reported only once for each function it appears in

有人可以解释这些错误的含义吗?据我所知,我在这行中声明了outputLength:

 int outputLength = sprintf(outputBuf, "%s/r/n/r/n%s/r/n", "HTTP/1.0 404 Not Found","<html><body><h1>404 Page Not Found</h1></body></html>");

我不确定在int之前会发生什么。至于标签错误,我不知道为什么我会这样,因为我不相信我在使用标签。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:6)

您不能在案例标签之间的中间声明。但是,您可以简单地引入一个新的本地范围,您可以在其中声明:

switch (errorNum)
{
    case 404:
    {
        //Send back a 404 error
        char outputBuf[MAXREQUESTLENGTH];
        int outputLength = /* ... */
        break;
    }
    case 405:
        foo();
        break;
    // ...
}
相关问题