Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Does it make any sense or not?

like image 935
Datoxalas Avatar asked Apr 05 '11 15:04

Datoxalas


3 Answers

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)

like image 84
Alexander Gessler Avatar answered Oct 01 '22 18:10

Alexander Gessler


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.

like image 27
Reed Copsey Avatar answered Oct 01 '22 17:10

Reed Copsey


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

like image 31
Lightness Races in Orbit Avatar answered Oct 01 '22 18:10

Lightness Races in Orbit