【问题标题】:What is wrong with my switch statement?我的 switch 语句有什么问题?
【发布时间】:2014-11-19 00:44:34
【问题描述】:

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

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

【问题讨论】:

  • 阅读 28:6 的错误,因为它确实告诉您出了什么问题。将声明移到开关之外,看看错误是否消失。
  • 如果错误消失了,正如@lurker 建议的那样,那么你有一个较旧的编译器,在 case 404: 语句之后放置一个'{',在 break 之前放置一个'}';陈述。但是我怀疑问题实际上是在 switch() 语句之前。变量errorNum 定义了吗?是否定义了常量 MAXREQUESTLENGTH? switch() 语句之前的语句是否以';'结尾?
  • 我建议添加一个 'default: // 处理错误中断;作为最后一种情况,一些较旧的编译器不会正确终止 switch() 范围,这样如果没有匹配到任何大小写,程序就会崩溃

标签: c compiler-errors switch-statement


【解决方案1】:

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

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

【讨论】:

  • 很抱歉,我并没有真正看到这与我正在做的事情之间的区别。我相信我也在案例中创建具有本地范围的变量,我不想在案例之外使用它们。
  • @guribe94:大括号!
猜你喜欢
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 2011-04-08
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
相关资源
最近更新 更多