Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating conditionals

How can we code conditional behavior without using if or ? (ternary operator) ?

One idea comes to mind:

for(;boolean_expression;) {
  // our code
  break;
}

Any others ?

like image 249
Agnius Vasiliauskas Avatar asked Feb 24 '23 15:02

Agnius Vasiliauskas


2 Answers

I hope what you dont want is just 'if' or 'ternary'.

#1

How about this:

Instead of : if (condition) printf("Hi");

Use:

condition && printf("Hi");

Short circuit evaluation. This is much similar to using if though.

#2

For if (condition) a(); else b();

Use:

int (*p[2])(void) = {b, a};
(p[!!condition])()

Using array of function pointers, and double negation.

#3

Yet another variant close to ternary operator (function, though)

ternary_fn(int cond, int trueVal, int falseVal){
    int arr[2];
    arr[!!cond] = falseVal;
    arr[!cond] = trueVal;
    return arr[0];
}

Use it like ret = ternary_fn(a>b, 5, 3) instead of ret = a > b ? 5 : 3;

like image 79
UltraInstinct Avatar answered Mar 07 '23 18:03

UltraInstinct


switch(condition){
  case TRUE:
    ourcode(); 
    break;
  default:
    somethingelse();
 }
like image 41
regularfry Avatar answered Mar 07 '23 17:03

regularfry