Simulation of conventions

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

The thought comes to mind:

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

Any others?

+4
source share
3 answers

Hope you don’t want it, it’s just “if” or “ternary”.

# 1

How about this:

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

Using:

 condition && printf("Hi"); 

Short circuit rating . This is very similar to using if , though.

# 2

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

Using:

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

Using an array of function pointers and double negation.

# 3

Another option close to the ternary operator (function, however)

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

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

+5
source
 switch(condition){ case TRUE: ourcode(); break; default: somethingelse(); } 
+2
source

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; } 

It depends on true Boolean expressions evaluating to 1, which is true for gcc, but I don't think it is guaranteed by the standard.

+1
source

Source: https://habr.com/ru/post/1346176/


All Articles