Converting bool to text in C++

前端 未结 15 2343
走了就别回头了
走了就别回头了 2020-12-01 04:17

Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to \"true\" and 0 turns to \"false\"? I could just use an if st

15条回答
  •  Happy的楠姐
    2020-12-01 04:45

    If you decide to use macros (or are using C on a future project) you should add parenthesis around the 'b' in the macro expansion (I don't have enough points yet to edit other people's content):

    #define BOOL_STR(b) ((b)?"true":"false")
    

    This is a defensive programming technique that protects against hidden order-of-operations errors; i.e., how does this evaluate for all compilers?

    1 == 2 ? "true" : "false"
    

    compared to

    (1 == 2) ? "true" : "false"
    

提交回复
热议问题