Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You actually <em>can</em> declare variables within a switch if you do it according to the syntax of the language. You're getting an error because "<code>case 0:</code>" is a label, and in C it's illegal to have a <strong>declaration</strong> as the first statement after a label — note that the compiler expects an <strong>expression</strong>, such as a method call, normal assignment, etc. (Bizarre though it may be, that's the rule.)</p> <p>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.</p> <hr> <p><strong>Edit:</strong></p> <p>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 <strong>for</strong>, <strong>while</strong>, or <strong>do</strong> loop, or even in <strong>if</strong> and <strong>else</strong> clauses. (In fact, this is covered in puzzler #55 of <a href="http://www.javapuzzlers.com/" rel="noreferrer">"Java Puzzlers"</a>, 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 <strong>switch</strong> / <strong>case</strong> constructs, though, some people omit the braces since the <strong>break</strong> statement is the critical statement for control flow.</p> <p>To see the compiler throw fits, copy this horrific, pointless snippet into your (Objective-)C code:</p> <pre><code>if (1) int i; else int i; for (int answer = 1; answer &lt;= 42; answer ++) int i; while (1) int i; do int i; while (1); </code></pre> <p>Yet another reason to always use { } braces to delimit the body of such constructs. :-)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload