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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With