c - 我的 switch 语句有什么问题?

标签 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 之前会发生什么。至于标签错误,我不确定为什么会这样,因为我不相信我在使用标签。任何帮助将不胜感激。

最佳答案

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

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

关于c - 我的 switch 语句有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27006986/

相关文章:

Swift - 在 switch 语句中绑定(bind)泛型参数

c - 初学者,带源代码的 C 语言 switch 中的字符串。可能的?

c# - 如何以编程方式向 Windows 应用程序提供输入?

c - 如何从 C 调用 CLAPACK?

javascript - Java脚本中出现意外的 token 错误,是否要正常运行?

compiler-errors - 链接函数调用与使用中间变量

c - 如何按字母顺序对数字进行排序?

c - 用C语言制作图表

java - 线程 “main”中的异常java.lang.NullPointerException

java - 使用 switch case 检查用户输入是字符串、整数还是 float