16

Does it make any sense or not?

Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861
Datoxalas
  • 1,193
  • 5
  • 13
  • 23

3 Answers3

35

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)

Alexander Gessler
  • 44,353
  • 6
  • 80
  • 121
  • 5
    Boolean is also a lot smaller in terms of memory. – Devin Burke Apr 05 '11 at 16:04
  • 3
    Just to add reference to what Justin Satyr is saying: Integer's are usually 4bytes (32bits) whereas Boolean's are 1byte (8bits). These are all dependant on the platform but for all of the main platforms I know this is correct. (Yes, a boolean should, in a perfect world, be 1 bit, however it's impossible to reference only one bit in memory) – Adam Casey Apr 05 '11 at 16:10
  • 3
    @Justin Satyr A lot smaller is std::vector compared to std::vector in other cases you need to take alignment into account. – Begemoth Apr 05 '11 at 16:11
  • Isn't std::vector secretly a bunch of bit flags though. – Roman A. Taycher Jun 02 '11 at 05:30
14

I recommend using true if your type is logically a boolean. This will be far more clear in terms of intent, which makes your code more maintainable.

Reed Copsey
  • 539,124
  • 75
  • 1,126
  • 1,354
3

For what? Use a boolean for a boolean; use an integer when you're counting something.

Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021