Is it a good idea to define a variable in a local block for a case of a switch statement?

Posted by Paperflyer on Stack Overflow See other posts from Stack Overflow or by Paperflyer
Published on 2010-04-07T18:58:42Z Indexed on 2010/04/07 19:03 UTC
Read the original article Hit count: 206

I have a rather long switch-case statement. Some of the cases are really short and trivial. A few are longer and need some variables that are never used anywhere else, like this:

switch (action) {
    case kSimpleAction:
        // Do something simple
        break;
    case kComplexAction: {
        int specialVariable = 5;
        // Do something complex with specialVariable
      } break;
}

The alternative would be to declare that variable before going into the switch like this:

int specialVariable = 5;
switch (action) {
    case kSimpleAction:
        // Do something simple
        break;
    case kComplexAction:
        // Do something complex with specialVariable
        break;
}

This can get rather confusing since it is not clear to which case the variable belongs and it uses some unnecessary memory.

However, I have never seen this usage anywhere else.
Do you think it is a good idea to declare variables locally in a block for a single case?

© Stack Overflow or respective owner

Related posts about c

    Related posts about switch-statement