I am new to learning C and I would like to know if it is possible to launch more than 1 instruction inside ternary oparator in C - for example:
int a = 5;
int b = 7;
int max;
int min;
max = (a>b) ? a, b = min : b, a = min;
pritnf("%d %d", min, max);
I want to sort those numbers and assign them to a variable max or min. Is it possible to tell the program that if a > b it will save a as maximum and assign b to minimum? Or do I have to do it using If function? I think the problem is in using the comma, but I dont know what should I use instead. The message I get is this:
warning: left operand of comma operator has no effect [-Wunused-value] int max = (a>b) ? (a, b = min) : (b, a = min);
The syntax of the conditional expression is:
conditional-expression:
logical-OR-expression
logical-OR-expression
?expression:conditional-expressionTherefore, you must use parentheses at least for the third operand because of operator precedence.
Furthermore, your assignments were incorrect.
Here is a modified version:
Output:
5 7To avoid compiler warnings, you could write:
Note however that this method is very unusual, confusing and error prone. Use the ternary operator to perform just one computation at a time:
or just use an
ifstatement:C is very versatile... Not every possibility is to be used and abused. Here are some more convoluted ones to avoid: