0

Just wanted to get your thought on this, I recall reading that property declarations are forbidden inside switch-case statements (i.e. case:ABC int i=0; is not allowed)

I came across something rather odd this morning,

the following compiles

switch(var1) {
  case 1:
    NSLog(@"hello");
    float x = 0;
    view.setCenter(CGPointMake(x,100));
    break;
  ...

whereas the following does NOT compile

switch(var1) {
  case 1:
    float x = 0;
    view.setCenter(CGPointMake(x,100));
    break;
  ...

So it seems if you start a case expression with a statement (not declaration), it compiles. But when you try to start right away with a variable declaration, it doesn't.

What is the rationale behind this?

EDIT: Decided to make my question clearer, what difference does NSLog make so that it compiles now?

jscs
  • 63,694
  • 13
  • 151
  • 195
Ege Akpinar
  • 3,266
  • 1
  • 23
  • 29

2 Answers2

4

The NSLog doesn't make a difference here. It's the ; that is making the difference:

switch(var1) {
    case 1:
        ;
        float x = 0;
        view.setCenter(CGPointMake(x,100));
        break;

compiles. Even

 switch(var1) {
    case 1:;
        float x = 0;
        view.setCenter(CGPointMake(x,100));
        break;

What cannot compile is float (or other type) immediately after :. In other words, a command is expected after :, not a declaration.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
0

It does compile if you:

switch(var1) {
  case 1:
  {
    float x = 0;
    view.setCenter(CGPointMake(x,100));
  }
    break;

As for the why check this answer.

Community
  • 1
  • 1
Rui Peres
  • 25,741
  • 9
  • 87
  • 137
  • I couldn't find in neither that SO post or the 'four switch oddities' post referred by it. My question is what difference does NSLog make – Ege Akpinar Apr 17 '13 at 12:58