开发者

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 ?


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;


switch(condition){
  case TRUE:
    ourcode(); 
    break;
  default:
    somethingelse();
 }


Using function pointers:

void ourcode(void){puts("Yes!");}
void somethingelse(void){puts("No!");}

void (*_if[])(void) = { somethingelse,ourcode };

int main(void){
  _if[1==1]();
  _if[1==0]();
  return 0;
}

This relies on true boolean expressions evaluating to 1, which happens to be true for gcc, but I don't think it is guaranteed by the standard.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜