K&Rを読もう(1) Hello, World(2)
Hello, Worldを僕なりに書き直してみる。
コンソールだけじゃつまらないので、ウィンドウに表示させようと思う。
・・・といっても、ウィンドウを出すのは面倒なので、テキストでエミュレートする。
#include <stdio.h> #include <stdlib.h> enum {CONSOLE, WINDOW}; /* ウィンドウのエミュレート */ static int message_box(const char *str) { printf("+--------------X+\n"); printf("| %s\n", str); printf("| O K |\n"); printf("+---------------+\n"); return 0; } typedef int (*say_t)(const char *); /* say_t型の宣言 */ /* 関数ポインタsay_t型を返す */ static say_t get_say(int type) { switch (type) { case CONSOLE: return puts; case WINDOW : return message_box; default: exit(EXIT_FAILURE); } } /* メイン */ int main(void) { say_t say; say = get_say(CONSOLE); say("hello, world"); say(""); /* 改行 */ say = get_say(WINDOW); say("hello, world"); exit(EXIT_SUCCESS); }
実行結果はこんな感じ。
hello, world +--------------X+ | hello, world | O K | +---------------+
でたぁ!!ウィンドウ!!
(閉じるボタン付き)
「関数を返す」ということが出来るだけで、これほど自由度が上がる。
関数ポインタ恐るべし。