开发者

Is using char as a bool in C bad practice?

Is there any downside to using

typedef char bool;
enum boolean { fal开发者_如何学Cse, true };

in C to provide a semantic boolean type?


In C99, you should be using stdbool.h, which defines bool, true, and false.

Otherwise what you have is fine. Using just the enum may be a bit simpler, but if you really want to save space what you have works.


The short answer is: it's fine. It's particularly good if you needed to make large arrays of them, although I would be tempted to just use the C99 built-in1.

Since you asked "is there any downside..." I suppose I could remark that there have been important machines that did not actually have a character load instruction. (The Cray and initial DEC Alpha come to mind.) Machines in the future may suddenly go all minimal once again.

It will always be fast to load a standard integral type.

It will probably always be fast to load a single character.


1. See C99 6.2.5. There is a built-in type _Bool. Then, if you include <stdbool.h> (see C99 7.16) you get an alias, the more gracefully named bool, and defines for true and false. If you use this it will clash with your typedef but I'm sure it would be an easy thing to fix.


The downside of typedef char bool; is that if you compile with a C99 implementation and happen to include <stdbool.h>, this ends up as typedef char _Bool;, which is wrong. Also, if you ever tried to compile the code as C++, you'd have issues (that's not necessarily a problem, but it could be).

It would probably better either to use <stdbool.h> if your implementation provides one or to use a different name for the type, like BOOL.


I would suggest using a bit to represent true or false, rather than a character. A character uses 8 bits, We can set 1 for true and 0 for false with just 1 bit. That will be more memory efficient and also satisfies the purpose. (e.g) char flag:1;

Reference : http://en.wikipedia.org/wiki/Bit_field

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜