1

I want to print number of variables based on mode value. Here is example:

char format[64] = {}
int mode_1, mode_2, mode_3;
int a,b,c,d,e,f;

...
// Get mode value here ....
...

// Build the format first
sprintf(format, "%s-%s-%s\n", mode_1 == 0 ? "a=%d,b=%d" : "a=%d",
                              mode_2 == 0 ? "c=%d,d=%d" : "c=%d",
                              mode_3 == 0 ? "e=%d,f=%d" : "e=%d");

// Print value here
printf(format, mode_1 == 0 ? (a,b) : a,
               mode_2 == 0 ? (c,d) : c,
               mode_3 == 0 ? (e,f) : f);

When I tried a simple example, the value printed when mode value is zero seems not right. What am I doing wrong here?

enter image description here

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Quang
  • 135
  • 2
  • 9
  • 4
    `When I tried a simple example` Please do not post screenshots. Please post text as text. – KamilCuk Oct 27 '20 at 09:33
  • `?:` is an operator and as such it has 1 result value. You cannot use it to evaluate to multiple values or even to different number of results in both cases. – Gerhardh Oct 27 '20 at 11:42

1 Answers1

1

This expression

(a, b)

is an expression with the comma operator. The result of the expression is the value of the last operand.

That is this call

printf(format, mode == 0 ? (a,b): a);

in fact is equivalent to the call

printf(format, mode == 0 ? b: a);

Instead you could write

mode == 0 ? printf(format, a, b ) : printf( format, a );

If the form of the call of printf depends on the integer variable mode then you could use for example a switch statement or if-else statements.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335