سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top