Using multiple integers with one operand in a C conditional statement possible?

97 views Asked by At

Is it possible in C to write something like? and if so how is it done?

if ( x != 1, 2, 7, 8, 90)
3

There are 3 answers

0
Gam On

No you can't do that. You need to write it like this :

if (x != 1 && x != 2 && x!= 3)

The comma operator has another effects, I let you looking for it :)

0
dbush On

You can't compare multiple values that way. You need to check each individually combined with the proper logical operator:

if ((x != 1) && (x != 2) && (x != 7) && (x != 8) && (x != 90)

What you wrote is something entirely different. This:

if ( x != 1, 2, 7, 8, 90)

Is a single comparison operator followed by several instances of the comma operator. The comma operator evaluates the left operand, discards the value, then evaluates the right operand and takes its value.

So that expression first evaluates x != 1 which will result in either 0 or 1. That value is discarded and the value 2 is evaluated. That value is in turn discarded and the next value (7) is evaluated. Then 8 is evaluated and discarded, then 90 is evaluated which becomes the value of the entire expression.

2
Jacek Cz On

My answer is paradoxical, but strictly correct.

Is it possible in C to write something like? and if so how is it done?

a) Yes, it is possible.

b) How is done? Here is comma operator, yes, C has comma operator. Final value is last element, 90 here

c) The question author didn't ask about comparison

So this if has sense if(90). Interesting is that sub-expression x!=1 is evaluated, but result is lost, and has no effect on final

if ( x != 1, 2, 7, 8, 90)
{
  here, true
}
else
{
  not here, false
}

Adan didn't ask how to compare, but the question posed above.

Appendix: fully working code from MSVC. Everything I say, anyone can debug.

#include "stdafx.h"


int main()
{
    int x = 2;
    int k = (x != 1, 2, 7, 8, 90);
    if (x != 1, 2, 7, 8, 90)
    {
        int k1 = 1;
    }
    else
    {
        int k2 = 2;
    }
    return 0;
}