本文介绍了声明在switch语句中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到几个回答这个问题,我得到它 - 你不能声明并分配开关里面的变量。但我想,如果下面是正确的抛出一个错误说

Code:

switch (i) {
    case 0:
        int j = 1;
        break;
}

Why would putting a call to NSLog() before it result in no errors?

switch (i) {
    case 0:
        NSLog(@"wtf");
        int j = 1;
        break;
}
解决方案

You actually can declare variables within a switch if you do it according to the syntax of the language. You're getting an error because "case 0:" is a label, and in C it's illegal to have a declaration as the first statement after a label — note that the compiler expects an expression, such as a method call, normal assignment, etc. (Bizarre though it may be, that's the rule.)

When you put the NSLog() first, you avoided this limitation. You can enclose the contents of a case in { } braces to introduce a scoping block, or you can move the variable declaration outside the switch. Which you choose is a matter of personal preference. Just be aware that a variable declared in { } braces is only valid within that scope, so any other code that uses it must also appear within those braces.


Edit:

By the way, this quirk isn't as uncommon as you might think. In C and Java, it's also illegal to use a local variable declaration as the lone statement (meaning "not surrounded by braces) in a for, while, or do loop, or even in if and else clauses. (In fact, this is covered in puzzler #55 of "Java Puzzlers", which I highly recommend.) I think we generally don't write such errors to begin with because it makes little sense to declare a variable as the only statement in such contexts. With switch / case constructs, though, some people omit the braces since the break statement is the critical statement for control flow.

To see the compiler throw fits, copy this horrific, pointless snippet into your (Objective-)C code:

if (1)
    int i;
else
    int i;
for (int answer = 1; answer <= 42; answer ++)
    int i;
while (1)
    int i;
do
    int i;
while (1);

Yet another reason to always use { } braces to delimit the body of such constructs. :-)

这篇关于声明在switch语句中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 19:07
查看更多