模拟条件

Agn*_*kas 4 c conditional conditional-statements

如何在使用if?(三元运算符)的情况编码条件行为?

想到一个想法:

for(;boolean_expression;) {
  // our code
  break;
}
Run Code Online (Sandbox Code Playgroud)

还有其他人?

Ult*_*nct 5

我希望你不想要的只是'if'或'ternary'.

#1

这个怎么样:

代替 : if (condition) printf("Hi");

使用:

condition && printf("Hi");
Run Code Online (Sandbox Code Playgroud)

短路评估.这与使用非常相似if.

#2

对于 if (condition) a(); else b();

使用:

int (*p[2])(void) = {b, a};
(p[!!condition])()
Run Code Online (Sandbox Code Playgroud)

使用函数指针数组和双重否定.

#3

另一个接近三元运算符的变量(函数虽然)

ternary_fn(int cond, int trueVal, int falseVal){
    int arr[2];
    arr[!!cond] = falseVal;
    arr[!cond] = trueVal;
    return arr[0];
}
Run Code Online (Sandbox Code Playgroud)

使用它ret = ternary_fn(a>b, 5, 3)而不是ret = a > b ? 5 : 3;

  • 它确保值始终为0或1,否则您可以将任何正值传递为true. (2认同)