Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Does Visual Studio Give the Warning "Relational Expression As Switch Expression"?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading