Home > Software design >  Can i do Multiple tasks by the conditional operator?
Can i do Multiple tasks by the conditional operator?

Time:12-19

Can we write multiple commands like in if statement {between brackets} in conditional operators ?

    if (x == 1) {
        printf("Printf");
        scanf("%d", &scanf);
        callFun(calling a function);
    }
    else if (x == 2) {
        printf("Printf2");
        scanf("%d", &scanf2);
        callFun2(calling a function);
    }

CodePudding user response:

int foo(int x)
{
    int g,h;
    (void)( x == 1 ? ( printf("Hello\n"), scanf("%d", &g), callfunc(g)) : x == 2 ? ( printf("Hello2\n"), scanf("%d", &k), callfunc(h   5)) : 0);
}

Very easy to read as you see. Better use ifs

CodePudding user response:

This looks clean in my opinion

#include <stdio.h>

void func(){
    puts("working");
}
void func1(){
    puts("working 2");
}

int main(){
    int i = 21;
    i == 2122 ? func() : func1();
    return 0;
}

This also works

int main(){
    int i = 21;
    i == 2122 ? (
            puts("working 1"),
            puts("working 2")
            ) : (
                puts("working 3"),
                puts("working 4"));
    return 0;
}

CodePudding user response:

It would be a weird and thus undesireable thing to do, but it can be done.

The key is to use a comma operator instead of separate statements.

(
   x == 1 ? (
      printf("Printf"),
      scanf("%d", &scanf),
      callFun(calling a function)
   )
   : x == 2 ? (
      printf("Printf2"),
      scanf("%d", &scanf2),
      callFun2(calling a function)
   )
   : (void)0
);
  • Related