Search code examples
cformatprintfconditional-operatorcomma-operator

Printf with conditional format


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


Solution

  • 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.