
Incomputer science, theBoolean (sometimes shortened toBool) is adata type that has one of two possible values (usually denotedtrue andfalse) which is intended to represent the twotruth values oflogic andBoolean algebra. It is named afterGeorge Boole, who first defined an algebraic system of logic in the mid-19th century. The Boolean data type is primarily associated withconditional statements, which allow different actions by changingcontrol flow depending on whether a programmer-specified Booleancondition evaluates to true or false. It is a special case of a more generallogical data type—logic does not always need to be Boolean (seeprobabilistic logic).
Inprogramming languages with a built-in Boolean data type, such asPascal,C,Python orJava, thecomparison operators such as> and≠ are usually defined to return a Boolean value.Conditional anditerative commands may be defined to test Boolean-valued expressions.
Languages with no explicit Boolean data type, likeC90 andLisp, may still represent truth values by some other data type.Common Lisp uses an emptylist for false, and any other value for true. The C programming language uses aninteger type, where relational expressions likei > j and logical expressions connected by&& and|| are defined to have value 1 if true and 0 if false, whereas the test parts ofif,while,for, etc., treat any non-zero value as true.[1][2] Indeed, a Boolean variable may be regarded (and implemented) as a numerical variable with one binary digit (bit), or as a bit string of length one, which can store only two values. The implementation of Booleans in computers are most likely represented as a fullword, rather than a bit; this is usually due to the ways computers transfer blocks of information.
Most programming languages, even those with no explicit Boolean type, have support for Boolean algebraic operations such asconjunction (AND,&,*),disjunction (OR,|,+),equivalence (EQV,=,==),exclusive or/non-equivalence (XOR,NEQV,^,!=,¬), andnegation (NOT,~,!,¬).
In some languages, likeRuby,Smalltalk, andAlice thetrue andfalse values belong to separateclasses, e.g.,True andFalse, respectively, so there is no one Booleantype.
InSQL, which uses athree-valued logic for explicit comparisons because of its special treatment ofNulls, the Boolean data type (introduced inSQL:1999) is also defined to include more than two truth values, so that SQLBooleans can store all logical values resulting from the evaluation of predicates in SQL. A column of Boolean type can be restricted to justTRUE andFALSE though.
One of the earliest programming languages to provide an explicitBOOLEAN data type isALGOL 60 (1960) with valuestrue andfalse and logical operators denoted by symbols '' (and), '' (or), '' (implies), '' (equivalence), and '' (not). Due to input device andcharacter set limits on many computers of the time, however, most compilers used alternative representations for many of the operators, such asAND or'AND'.
This approach withBOOLEAN as a built-in (eitherprimitive or otherwise predefined)data type was adopted by many later programming languages, such asSimula 67 (1967),ALGOL 68 (1970),[3]Pascal (1970),Ada (1980),Java (1995), andC# (2000), among others.
Initial implementations of the languageC (1972) provided no Boolean type, and to this day Boolean values are commonly represented by integers (ints) in C programs. The comparison operators (>,==, etc.) are defined to return a signed integer (int) result, either 0 (for false) or 1 (for true). Logical operators (&&,||,!, etc.) and condition-testing statements (if,while) assume that zero (and hence aNULL pointer or anull string terminator '\0' also) is false and all other values are true.
Afterenumerated types (enums) were added to theAmerican National Standards Institute version of C,ANSI C (1989), many C programmers got used to defining their own Boolean types as such, for readability reasons. However, enumerated types are equivalent to integers according to the language standards; so the effective identity between Booleans and integers is still valid for C programs.
StandardC (sinceC99) provides a Boolean type, called_Bool. SinceC23, the Boolean is now a core data type calledbool, with valuestrue andfalse (previously these were provided by macros from the headerstdbool.h, which is now obsolete). The language guarantees that any two true values will compare equal (which was impossible to achieve before the introduction of the type). Boolean values still behave as integers, can be stored in integer variables, and used anywhere integers would be valid, including in indexing, arithmetic, parsing, and formatting. This approach (Boolean values are just integers) has been retained in all later versions of C. Note, that this does not mean that any integer value can be stored in a Boolean variable.
C++ has had the Boolean data typebool sinceC++98, but with automatic conversions from scalar and pointer values that are very similar to those of C. This approach was adopted also by many later languages, especially by somescripting languages such asAWK.
TheD programming language has a proper Boolean data typebool. Thebool type is a byte-sized type that can only hold the value true or false.The only operators that can accept operands of type bool are:&, |, ^, &=, |=, ^=, !, &&, || and?:.Abool value can be implicitly converted to any integral type, with false becoming 0 and true becoming 1.The numeric literals 0 and 1 can be implicitly converted to the bool values false and true, respectively. Casting an expression tobool means testing for 0 or!=0 for arithmetic types, andnull or!=null for pointers or references.
Objective-C also has a separate Boolean data typeBOOL, with possible values beingYES orNO, equivalents of true and false respectively.[4] Also, in Objective-C compilers that support C99, C's_Bool type can be used, since Objective-C is asuperset of C.
Forth (programming language) has no Boolean type, it uses regular integers: value 0 (all bits low) represents false, and -1 (all bits high) represents true. This allows the language to define only one set of logical operators, instead of one for mathematical calculations and one for conditions.[5]
The first version ofFORTRAN (1957) and its successorFORTRAN II (1958) have no logical values or operations; even the conditionalIF statement takes an arithmetic expression and branches to one of three locations according to its sign; seearithmetic IF.FORTRAN IV (1962), however, follows the ALGOL 60 example by providing a Boolean data type (LOGICAL), truth literals (.TRUE. and.FALSE.), logicalIF statement, Boolean-valued numeric comparison operators (.EQ.,.GT., etc.), and logical operators (.AND.,.OR., and.NOT.). InFORMAT statements, a specific format descriptor ('L') is provided for the parsing or formatting of logical values. A common extension prior toFORTRAN 77 was to extend the.EQ. and.NE. operators, or perhaps add a.XOR. operator for comparing Boolean expressions.[6] Fortran 77 added.EQV. and.NEQV. operators to standardize the operations. Fortran 90 added alternative comparison operators<,<=,==,/=,>, and>=.
InJava, the value of theboolean data type can only be eithertrue orfalse.[7]
InUnity, the value of theboolean (also known as the bool) can be eithertrue orfalse and is used in scripting.
The languageLisp (1958) never had a built-in Boolean data type. Instead, conditional constructs likecond assume that the logical valuefalse is represented by the empty list(), which is defined to be the same as the special atomnil orNIL; whereas any others-expression is interpreted astrue. For convenience, most modern dialects of Lisp predefine the atomt to have valuet, so thatt can be used as a mnemonic notation fortrue.
This approach (any value can be used as a Boolean value) was retained in most Lisp dialects (Common Lisp,Scheme,Emacs Lisp), and similar models were adopted by manyscripting languages, even ones having a distinct Boolean type or Boolean values; although which values are interpreted asfalse and which aretrue vary from language to language. In Scheme, for example, thefalse value is an atom distinct from the empty list, so the latter is interpreted astrue. Common Lisp, on the other hand, also provides the dedicatedboolean type, derived as a specialization of the symbol.[8]
The languagePascal (1970) popularized the concept of programmer-defined enumerated types, previously available with different nomenclature inCOBOL,FACT andJOVIAL. A built-inBoolean data type was then provided as a predefined enumerated type with valuesFALSE andTRUE. By definition, all comparisons, logical operations, and conditional statements applied to and/or yieldedBoolean values. Otherwise, theBoolean type had all the facilities which were available for enumerated types in general, such as ordering and use as indices. In contrast, converting betweenBooleans and integers (or any other types) still required explicit tests or function calls, as in ALGOL 60. This approach (Boolean is an enumerated type) was adopted by most later languages which had enumerated types, such asModula,Ada, andHaskell.
Perl has no Boolean data type. Instead, any value can behave as Boolean in Boolean context (condition ofif orwhile statement, argument of&& or||, etc.). The number0, thestrings"0" and"", the empty list(), and the special valueundef evaluate to false.[9] All else evaluates to true.
Lua has a Boolean data type, but non-Boolean values can also behave as Booleans. The non-valuenil evaluates to false, whereas every other data type value evaluates to true. This includes the empty string"" and the number0, which are very often consideredfalse in other languages.
PL/I has no Boolean data type. Instead, comparison operators generate BIT(1) values; '0'B representsfalse and '1'B representstrue. The operands of, e.g.,&,|,¬, are converted to bit strings and the operations are performed on each bit. Theelement-expression of anIF statement is true if any bit is 1.
Python, from version 2.3 forward, has abool type which is asubclass ofint, the standard integer type.[10] It has two possible values:True andFalse, which arespecial versions of 1 and 0 respectively and behave as such in arithmetic contexts. Also, a numeric value of zero (integer or fractional), the null value (None), the empty string, and empty containers (lists,sets, etc.) are considered Boolean false; all other values are considered Boolean true by default.[11] Classes can define how their instances are treated in a Boolean context through the special method__nonzero__ (Python 2) or__bool__ (Python 3). For containers,__len__ (the special method for determining the length of containers) is used if the explicit Boolean conversion method is not defined.
InRuby, in contrast, onlynil (Ruby's null value) and a specialfalse object arefalse; all else (including the integer 0 and empty arrays) istrue.
Rexx has no Boolean data type. Instead, comparison operators generate 0 or 1; 0 representsfalse and 1 representstrue. The operands of, e.g.,&,|,¬, must be 0 or 1.
Booleans appear in SQL when acondition is needed, such asWHERE clause, in form of predicate which is produced by using operators such as comparison operators,IN operator,IS (NOT) NULL etc. However, apart fromTRUE andFALSE, these operators can also yield a third state, calledUNKNOWN, when comparison withNULL is made.
The SQL92 standard introducedIS (NOT) TRUE, IS (NOT) FALSE, andIS (NOT) UNKNOWN operators which evaluate a predicate, which predated the introduction of Boolean type inSQL:1999.
The SQL:1999 standard introduced aBOOLEAN data type as an optional feature (T031). When restricted by aNOT NULL constraint, a SQLBOOLEAN behaves like Booleans in other languages, which can store onlyTRUE andFALSE values. However, if it is nullable, which is the default like all other SQL data types, it can have the special null value also. Although the SQL standard defines threeliterals for theBOOLEAN type –TRUE, FALSE, andUNKNOWN — it also says that theNULL BOOLEAN andUNKNOWN "may be used interchangeably to mean exactly the same thing".[12][13] This has caused some controversy because the identification subjectsUNKNOWN to the equality comparison rules for NULL. More preciselyUNKNOWN = UNKNOWN is notTRUE butUNKNOWN/NULL.[14] As of 2012 few major SQL systems implement the T031 feature.[15] Firebird andPostgreSQL are notable exceptions, although PostgreSQL implements noUNKNOWN literal;NULL can be used instead.[16]
The treatment of Boolean values differs between SQL systems.
For example, inMicrosoft SQL Server, Boolean value is not supported at all, neither as a standalone data type nor representable as an integer. It shows the error message "An expression of non-Boolean type specified in a context where a condition is expected" if a column is directly used in theWHERE clause, e.g.SELECTaFROMtWHEREa, while a statement such asSELECTcolumnISNOTNULLFROMt yields a syntax error. TheBIT data type, which can only store integers 0 and 1 apart fromNULL, is commonly used as a workaround to store Boolean values, but workarounds need to be used such asUPDATEtSETflag=IIF(colISNOTNULL,1,0)WHEREflag=0 to convert between the integer and Boolean expression.
Microsoft Access, which uses theAccess Database Engine (ACE/JET),[17] also does not have a Boolean data type.Similar to MS SQL Server, it uses aBIT data type.[18] In Access it is known as a Yes/No data type[19] which can have two values; Yes (True) or No (False).The BIT data type in Access can also be represented numerically:True is −1 and False is 0.[20]This differs from MS SQL Server in two ways, even though both are Microsoft products:
PostgreSQL has a distinctBOOLEAN type as in the standard,[21] which allows predicates to be stored directly into aBOOLEAN column, and allows using aBOOLEAN column directly as a predicate in aWHERE clause.
InMySQL,BOOLEAN is treated as an alias ofTINYINT(1);[22]TRUE is the same as integer 1 andFALSE is the same as integer 0.[23]Any non-zero integer is true in conditions.
Tableau Software has a BOOLEAN data type.[24] The literal of a Boolean value isTrue orFalse.[25]
The TableauINT() function converts a Boolean to a number, returning 1 for True and 0 for False.[26]
Tcl has no separate Boolean type. Like in C, the integers 0 (false) and 1 (true—in fact any nonzero integer) are used.[27]
Examples of coding:
setv1if{$v}{puts"V is 1 or true"}
The above will showV is 1 or true since the expression evaluates to 1.
setv""if{$v}....
The above will render an error, as variablev cannot be evaluated as 0 or 1.
In some programming languages, anyexpression can be evaluated in a context that expects a Boolean data type. Typically (though this varies by programming language) expressions like the numberzero, theempty string, empty lists, andnull are treated as false, and strings with content (like "abc"), other numbers, and objects evaluate to true. Sometimes these classes of expressions are called falsy and truthy. For example, inLisp,nil, the empty list, is treated as false, and all other values are treated as true. InC, the number 0 or 0.0 is false, and all other values are treated as true.
InJavaScript, the empty string (""),null,undefined,NaN,+0,−0 andfalse[28] are sometimes calledfalsy (of which thecomplement istruthy) to distinguish between strictlytype-checked andcoerced Booleans (see also:JavaScript syntax#Type conversion).[29] As opposed to Python, empty containers (arrays, maps, sets) are considered truthy. Languages such asPHP also use this approach.
{{cite web}}: CS1 maint: numeric names: authors list (link)