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.
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 andif ( 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