Home > database >  Ternary Conditional Control
Ternary Conditional Control

Time:01-22

I have a question regarding Ternary Conditional in C. How can I do this if-else statement in Ternary Conditional?

if (argc <= 1) {
        printf("Something");
        printf("Something");
        func(NULL);
    } else {
        for (int i = 1; i < argc; i  ) {
            fun2(argv[i]);
        }
}

CodePudding user response:

Since the parameters of the ternary are expressions, and loops are not expressions, you can't put the printing loop directly in the ternary.

But a function call is an expression, so you can put a call to a function that prints the arguments into the ternary.

int print_args(int argc, char *argv[]) {
    for (int i = 1; i < argc; i  ) {
        fun2(argv[i]);
    }
}

argc <= 1 ? 
    (printf("Something"), printf("Something"), func(NULL)) :
    print_args(argc, argv);

CodePudding user response:

You cannot do it with standard C, as noted in the other answer. But there are some compiler extensions that can make it possible. GCC has a "Statement-expression" extension that allows a braces-enclosed block to return a value as an expression, which makes it possible to use it in the conditional construct. So your example is conversion is almost straight-forward:

 (argc <= 1) ? ({
    printf("Something");
    printf("Something");
    func(NULL);
 }) : ({
    for (int i = 1; i < argc; i  ) {
        fun2(argv[i]);
    }});

Or for those who want a fully compilable example:

#include <stdio.h>

void func(void *p) {}
void fun2(void *p) {}

int main(int argc, char**argv) {
     (argc <= 1) ? ({
        printf("Something");
        printf("Something");
        func(NULL);
     }) : ({
        for (int i = 1; i < argc; i  ) {
            fun2(argv[i]);
        }});
    return 0;
}

NOTE: The fact you can do it does not mean you should. Ternary conditionals are tending to be less readable than your conventional if/else statements, and overcomplicating them do not help it at all.

  •  Tags:  
  • Related