2014年4月9日 星期三

如何自定bool type

現在的code竟然沒有bool type,
上網找了一下,
有以下幾個方式可以自己定義。

Option 1

typedef int bool;
#define true 1
#define false 0

Option 2
typedef int bool;
enum { false, true };

Option 3
typedef enum { false, true } bool;

Option 4 (C99)
#include <stdbool.h>

Explanation
Options 1, 2 and 3 will have in practice the same identical behavior. #2 and #3 don't use #defines though, which in my opinion is better.
Option 4 will work only if you use C99 and it's the "standard way" to do it. Choose this if possible.
If you are undecided, go with #3!

參考資料:
C doesn't have any built in boolean types. What's the best way to use them in C?

沒有留言: