Device Monitoring Studio - Monitor, log and analyze data coming through PC ports and connections
Download Device Monitoring Studio Hide this button

switch Statement

switch statement has the following syntax:

statement-switch:
switch (sw-expr)
{
    case const-case-expr1:
        statement-block *
    [case const-case-expr2:
        statement-block *
    …
    ]
    [default:
        statement-block +
    ]
}
WARNING

switch statement's block must not be followed by a ‘;’ character!

switch statement is evaluated according to the following procedure:

  1. All const-case-exprN expressions are evaluated at compile time. If they fail to compute to a constant value, compilation error occurs. If you need to use non-const expressions, consider using the case_union.
  2. sw-expr is evaluated at run time.
  3. The resulting value is compared with each const-case-exprN value one by one until a match is found. If the match is not found, statement-block after the “default:” label is evaluated, if present.
  4. If the match is found, all statement blocks after the corresponding “case” label are evaluated, until the “default:” label, end of switch statement or a break statement are met.
struct A
{
    BYTE type;
    switch (type)
    {
        case 0:
            int value;
            break;
        case 1:
            double value;
            break;
        case 2:
            string value;
            break;
        default:
            $assert("Invalid file");
      }    // note: no ';' allowed here!
};