Why #define TRUE (1==1) in a C boolean macro instead of simply as 1?

前端 未结 8 1431
清歌不尽
清歌不尽 2020-12-12 11:55

I\'ve seen definitions in C

#define TRUE (1==1)
#define FALSE (!TRUE)

Is this necessary? What\'s the benefit over simply defining TRUE as

8条回答
  •  甜味超标
    2020-12-12 12:31

    Aside from C++ (already mentioned), another benefit is for static analysis tools. The compiler will do away with any inefficiencies, but a static analyser can use its own abstract types to distinguish between comparison results and other integer types, so it knows implicitly that TRUE must be the result of a comparison and should not be assumed to be compatible with an integer.

    Obviously C says that they are compatible, but you may choose to prohibit deliberate use of that feature to help highlight bugs -- for example, where somebody might have confuse & and &&, or they've bungled their operator precedence.

提交回复
热议问题