#define TRUE !FALSE vs #define TRUE 1

前端 未结 6 1593
粉色の甜心
粉色の甜心 2021-01-18 02:31

Putting aside the fact that since c99 the stdbool.h has existed, when defining macros to handle Boolean types in C is there any difference between the following

6条回答
  •  南方客
    南方客 (楼主)
    2021-01-18 03:20

    In the C language, TRUE is properly defined as (!FALSE) because while zero (0) is FALSE and FALSE is zero (0), any other value is TRUE. You can use almost any variable as a boolean expression, and if it is non-zero the value of the expression is TRUE. A NULL pointer is zero for just that reason. So is the end-of-string character ('\0'). There is a great deal of code written to take advantage of that fact. Consider:

    while ( *d++ = *s++ ); 
    

    The copy will end when the end-of-string character is copied. This idiom is very common. Never mind the buffer size issues.

    This is one reason why it is a bad idea to test for equality to TRUE if you do not have a modern dedicated boolean type where the only possible values are TRUE and FALSE. I suggest you make it a habit to test for inequality to FALSE anyway, for safety's sake. You may not always get to work with the new and shiny.

提交回复
热议问题