multiple values in 1 if statement

Hello,

I want an if statement with multiple values,

Will it work like this? It doesn't give an error

if (x == 12 || x == 16 || x == 19 || ...)


or like this

if ((17,18,19,20 == val))

The first one is correct. The second one - I have never seen this in C++.

thehardwareman:
The first one is correct. The second one - I have never seen this in C++.

Okay thank you!

rico459:
or like this

if ((17,18,19,20 == val))

This is equivalent to:

if (17) // This 'if' will always be 'true' since 17 is not zero

The 'comma operator' (using a comma in an expression) evaluates both sides and returns the left side.

Are your values arbitrary, or do they follow a pattern? You can make expressions to test a pattern, for example your second one could be:

if (val >= 17 and val <=20)

If you had a regular series:
12, 16, 20, 24, 28, 32
you could test like:

if (val/4 >= 3 and val/4 <= 8)

johnwasser:
This is equivalent to:

if (17) // This 'if' will always be 'true' since 17 is not zero

The 'comma operator' (using a comma in an expression) evaluates both sides and returns the left side.

No, the last value is used, so it is equivalent to

if (val == 20)

rico459:
Will it work like this? It doesn't give an error

A useful exercise here would be to design an experiment to find out

oqibidipo:
No, the last value is used, so it is equivalent toif (val == 20)

Oops, you're right. My mistake.