Is using char as a bool in C bad practice?

后端 未结 4 1112
逝去的感伤
逝去的感伤 2021-02-19 21:35

Is there any downside to using

typedef char bool;
enum boolean { false, true };

in C to provide a semantic boolean type?

4条回答
  •  梦如初夏
    2021-02-19 22:04

    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 (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.

提交回复
热议问题