Function parameter as case in switch statement

The title was a little too vague for google.

I found myself planning to write this switch statement multiple times so I wanted to move it into a function.

What I'm looking to do is create a function that takes a value, what you expect the value to be, and a string identifier for the value.

bool checkValue(int value, uint8_t expected, char * id) {
    switch (value) {
        case expected:
            return true;
        case -1:
            printf("Error: Timeout on %srn", id);
        default:
            printf("Error: %s=%02xrn", id, value);
            return false;
    }
}

The compiler complains that the "expression must have a constant value" on the case expected: line. Now, I know I could change this to a series of if s but I'm interested in why this is doesn't work, or if there is a way to make it work.

Are switch statements just compiled in a way that makes it impossible to substitute a variable into a case value?


The compiler error pretty much tells you why it's forbidden. It's covered in 6.4.2 [stmt.switch]:

2 The condition shall be of integral type, enumeration type, or of a class type for which a single non-explicit conversion function to integral or enumeration type exists (12.3). [...] Any statement within the switch statement can be labeled with one or more case labels as follows:

case constant-expression :

where the constant-expression shall be a converted constant expression (5.19) of the promoted type of the switch condition. No two of the case constants in the same switch shall have the same value after conversion to the promoted type of the switch condition.


You cannot do that. A switch statement requires that all the case values be explicit constant expressions — intuitively, expressions whose value can be determined just by looking at them.

This is actually a feature: when I see a switch , I immediately know that the flow of control is not going to depend on runtime values. If the values change at runtime, a different idiom is used, the continued conditional:

if(value == expected) {
    return true;
} else if(value == -1) {
    printf("Error: Timeout on %srn", id);
    return false;
} else {
    printf("Error: %s=%02xrn", id, value);
    return false;
}

It is just a requirement by C. value has to be constant. Just change the case into an if-elseif-else statement.

链接地址: http://www.djcxy.com/p/84392.html

上一篇: Arduino(C)

下一篇: 功能参数作为switch语句中的情况