This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Switch Case Statement problem

I am using switch statement as follows

uint16 val;

switch (val)
{ case 0x0000:
...
break
case 0x0001:
...
break
case 0x0000:
...
break
case 0x0000:
...
break
case 0x0000:
...
break
case 0x0004:
...
break
case 0x0005:
...
break
case 0x0304:
break;

default:
break
}

some times control jumps from one case to other case eventhough there are break statements for each case.

Thanks
Pankaj

  • "some times control jumps from one case to other case eventhough there are break statements for each case."

    Probably because the Optimiser has spotted that there is common code shared between cases...?

  • Are you really sure that you have a switch statement with multiple case 0x0000? Each case statement must be unique - and the compiler will refuse to accept code with duplicated case values.

    As Andy notes - the compiler can perform a lot of reordering of the code to optimize for size or speed. It will detect case statements that have identical code or ends with identical code, and then decide if it should combine these code sequences. It is cheapest for the optimizer to combine the sequences if you already have jump in the code block - then the jump can jump to common code in another code block just as well as it can jump to code in the same code block.

  • its:

    case val:
    break;

    note semicolon after break ; is missing in most of your code

  • I am sorry there is correction in this piece of code
    I missed values, I wanted to show the sample code as the actual code is quite big.

    uint16 val;

    switch (val)
    { case 0x0001:
    ...
    break;
    case 0x0010:
    ...
    break;
    case 0x0020:
    ...
    break;
    case 0x0030:
    ...
    break;
    case 0x0100:
    ...
    break;
    case 0x0004:
    ...
    break;
    case 0x0205:
    ...
    break;
    case 0x0304:
    break;

    default:
    break;
    }

    What happens when I execute this and debug it then control goes to one case and then jumps to the another case though each case has a break, syntax and all are correct, no compile time errors.

  • to set the opimization to 2 and see what happens.
    That will (in)validate one possiblity.

    come back with the result

    Erik

  • The processor is not processing source code.

    And there is not a one-to-one relationship between source code statements and processor instructions.

    Don't assume that the processor execution will follow linearly from your source code. Most definitely don't support this if compiling with optimization turned on.