Last active
November 26, 2015 12:52
-
-
Save macrat/fdb74c122c8f9e22d225 to your computer and use it in GitHub Desktop.
forもwhileもifもswitchも、分岐する文を全て使わずにループを書きたかった。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| void void_func(int v){ | |
| } | |
| void loop(int i){ | |
| printf("hello, world! %d\n", i); | |
| ((void (*)(int))((long long)loop * (i<9) + (long long)void_func * (i>=9)))(i + 1); | |
| } | |
| int main(){ | |
| loop(0); | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 改良してみた版 | |
| #include <stdio.h> | |
| void end(int i){ | |
| } | |
| void loop(int i){ | |
| printf("hello, world! %d\n", i); | |
| (void (*[])(int)){end, loop}[i < 9](i + 1); | |
| } | |
| int main(){ | |
| loop(0); | |
| return 0; | |
| } |
具体的にはこーする
暇だったので書いた
#include <stdio.h>
void end(__attribute__((unused)) int i){}
void loop(int i) {
void (*ft[])(int) = {end, loop};
printf("hello, world! %d\n", i);
ft[i < 9](i + 1);
}
int main() {
loop(0);
return 0;
}
Author
なるほどな? 綺麗だ。
なるほど関数ポインタ配列の変数名書かなくても良いのか…
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
自分なら関数ポインタを配列に突っ込んで添字で(i < 9)する
そうすれば比較が1回で済む
好みの問題だけど