C doesn't have a bool? Also VS2010 question

前端 未结 6 1882
礼貌的吻别
礼貌的吻别 2021-01-12 16:17

I\'m using VS 2010 Pro.

First, C doesn\'t have a bool type? I just have to use int with 0/1. Seems odd as most languages consider boolean a standard type.

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 16:48

    C did not have an actual Boolean type until C99.

    As a result, idiomatic C doesn't really use boolean-valued symbols or expressions as such (i.e., you won't see many explicit tests against "true" or "false"). Instead, any zero-valued integral expression or a NULL pointer will evaluate to "false", and any non-zero-valued integral expression or a non-NULL pointer will evaluate to "true". So you'll see a lot of code like:

    foo *bar = malloc(sizeof *bar * ...);
    if (bar) // equivalent to writing bar != NULL
    {
       // bar is non-NULL
    } 
    

    Relational and equality expressions such as a == b or c < d will evaluate to an integral type with a value of either 1 (true) or 0 (false).

    Some people introduce their own TRUE or FALSE symbolic constants by doing something like

    #define TRUE  (1)  // or (!FALSE), or (1==1), or...
    #define FALSE (0)  // or (!TRUE), or (1==0), or ...
    

    Unforunately, some of those people occasionally manage to misspell 0 or 1 (or the expressions that are supposed to evaluate to 0 or 1); I once spent an afternoon chasing my tail because someone screwed up and dropped a header where TRUE == FALSE.

    Not coincidentally, that was the day I stopped using symbolic constants for Boolean values altogether.

提交回复
热议问题