Yawn
Yawn

Reputation: 173

How can I use the conditional operator to print an integer or a string value

In C how can I use a conditional operator inside of a printf statement utilizing two different data types? I would like to have the code below printing nothing instead of zero each time it encounters a even number. I would also like to be able to print a string when it encounters certain numbers.

I tried type casting (char)list[i] but that results in an incompatiable type cast because the printf statement requires an integer.

Print only odd values

int fail = 0;

    int list[] = {1, 2, 3, -1, 4};
    int size = sizeof(list) / sizeof(list[0]);

    for(int i = 0; i < size; i++) {
        if(list[i] == -1) {
            break;
        }
        printf("%d\n", (list[i] % 2 == 0) ? (i) : (fail));
    }

Upvotes: 1

Views: 4471

Answers (1)

rici
rici

Reputation: 241881

The correct and readable approach is to use several calls to printf, each with its own format and arguments:

if (list[i] % 2 == 0) {
  printf("%d\n", i);
}
else if (i == 42) {
  puts("The answer");
}
/* Otherwise, print nothing */

You could also do that with the ?: operator:

(list[i] % 2 == 0) ? printf("%d\n", i) :
(i = 42)           ? printf("%s\n", "The answer") :
                     0;

(This works because all three possible return values are the number of characters printed.)

If you just want to print 0 as nothing instead of 0, use 0 as the precision (not the width) of the format specifier:

printf("%.0d\n", i);

(In obfuscated code, you could force the value you wanted to hide to be 0 with a ternary operator. Or even with a multiply.)

C is a strongly-typed language, which means that the compiler needs to be able to deduce the type of any expression. That includes ?: expressions, so it is not possible for the second and third arguments of that operator to have incompatible types.

Upvotes: 3

Related Questions