fizzy drink - 1 month ago 9
C Question

set 2 values in a ternary operation - C

I'm having trouble setting two ints using ternary operators in C. I can't seem to find an answer as most questions relate to multiple ternary conditions.

Whereas, I want to check for one condition and set 2 values accordingly.

Ie:

``````if ( i == 5 ) {
x = foo;
y = foo + 1;
} else {
x = bar;
y = bar + 1;
}
``````

so far I tried the following, but it doesn't seem to work.

``````x, y = ( i == 5 ) ? foo, foo + 1 : bar, bar + 1;
``````

is it possible to set two values in ternary after checking 1 condition?

thanks,

This is not possible. Unlike python or perl which supports assigning to a list of numbers, C does not support this syntax.

You'll need two separate ternary operations to do this:

``````x = (i == 5) ? foo : bar;
y = (i == 5) ? foo + 1 : bar + 1;
``````

In the case that you only want the conditional to run once (e.g. it's a function call or some other expensive operation):

``````int result = (i == 5);
x = result ? foo : bar;
y = result ? foo + 1 : bar + 1;
``````

EDIT:

If you want to use something a bit ugly, this would work:

``````x = (i == 5) ? (y = foo + 1, foo) : (y = bar + 1, bar);
``````

By using the comma operator, the left side of the operator is evaluated (in this case, an assignment to `y`) and discarded while the right side becomes the value of the expression which subsequently gets assigned to `x`.

Note that the parenthesis are not strictly needed for the "if" portion, but they are needed for the "else" portion.

This is an abuse of the language however. Better to stick with something more readable.

Source (Stackoverflow)