本文介绍了预期表达式之前 ... 在 Switch 语句中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此代码块中遇到编译错误:

I am getting a compilation error in this block of code:

switch(event) {
    case kCFStreamEventHasBytesAvailable:
        UInt8 buf[BUFSIZE];
        CFIndex bytesRead = CFReadStreamRead(stream, buf, BUFSIZE);
        if (bytesRead > 0) {
            handleBytes(buf, bytesRead);
        }
        break;
    case kCFStreamEventErrorOccurred:
        NSLog(@"A Read Stream Error Has Occurred!");
    case kCFStreamEventEndEncountered:
        NSLog(@"A Read Stream Event End!");
    default:
        break;
}

UInt8 buf[BUFSIZE]; 导致编译器抱怨UInt8 之前的预期表达式"为什么?

The line UInt8 buf[BUFSIZE]; is causing the compiler to complain "Expected expression before UInt8" Why?

谢谢!

推荐答案

Switch 语句不会引入新的作用域.更重要的是,根据 C 语言规范,常规语句必须跟在 case 语句之后——不允许变量声明.您可以在变量声明之前放置一个 ; 并且编译器会接受它,但是您定义的变量将在 switch 父级的范围内,这意味着您不能在另一个变量中重新声明该变量案例陈述.

Switch statements don't introduce new scopes. What's more, according to the C language spec, a regular statement must follow a case statement - a variable declaration is not allowed. You could put a ; before your variable declaration and the compiler would accept it, but the variable that you defined would be in the scope of the switch's parent, which means you cannot re-declare the variable inside another case statement.

通常,当在 case 语句中定义变量时,会为 case 语句引入一个新的作用域,如

Typically when one defines variables inside of case statements, one introduces a new scope for the case statement, as in

switch(event) {
    case kCFStreamEventHasBytesAvailable: {
        // do stuff here
        break;
    }
    case ...
}

这篇关于预期表达式之前 ... 在 Switch 语句中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:31