Which value is better to use? Boolean true or Integer 1?

前端 未结 3 1534
猫巷女王i
猫巷女王i 2021-02-05 15:15

Does it make any sense or not?

3条回答
  •  灰色年华
    2021-02-05 15:51

    A boolean true is, well, a boolean value. Use it whenever you want to express that a certain binary condition is met.

    The integer literal 1 is a number. Use it, whenever you are counting something.

    Don't use integers for booleans and vice versa. They are different.

    Consider a variable int isEnabled. Of course, I can guess that 0 and 1 may be the only intended values for this variable. But language-wise, nothing keeps me from assigning 4247891. Using a boolean, however, restricts the valid values to true and false. This leaves no room for speculation.

    (C++ int's and bools are somewhat convertible, but it's generally frowned upon)

提交回复
热议问题