skip to Main Content

I have the following code:

float x = 0.43;
float y = 1.56;
size_t largerValueIndex = 1;
size_t smallerValueIndex = 0;
switch (x > y) {
case 1:
    largerValueIndex = 0;
    smallerValueIndex = 1;
    break;
}

Visual Studio issues the warning "C4144: ‘>’: relational expression as switch statement".

What I’d like to know is why is the warning necessary? I was under the impression that most switch and if statements are comparisons between two values. Is this considered bad practice? And if so, why?

My question has to do with the value being used as the switch expression, not those in the cases.

2

Answers


  1. Although the code is correct, switch is normally used for scenarios with more than two possible outcomes; a test with only two possible outcomes should be an if.

    The compiler warns about this because the unexpected use of switch might indicate a typo or a logic error.

    Login or Signup to reply.
  2. The expression (x >y) evaluates to boolean true and false, which convert to 0 and 1 as noted by @paddy and @user4581301 (see https://timsong-cpp.github.io/cppwp/conv.integral#2)

    While switch ( -relational expression- ) is legal, is is not normally used because there are only two values and if ( expression ) { ...true code... } else { ...false code... } is easier to understand.

    switch is normally used for one integer variable or expression to efficiently list the expected values instead of a long chain of if...else if...else if...else

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search