布尔型
维基百科,自由的百科全书
在计算机科学中,布尔数据类型又称为逻辑数据类型,是一种只有两种取值的原始類型:非零(通常是1或者-1)和零(分别等价于真和假)。
在一些语言中,布尔数据类型被定义为可代表多于两个真值。例如,ISO SQL:1999标准定义了一个SQL布尔型可以储存三个可能的值:真,假,未知(SQL null被当作未知真值来处理,但仅仅在布尔型中使用)。
这种数据类型在布尔和其他运算中使用,如与(AND
, &
, *
),或 (OR
, |
, +
),异或 (xor
, NEQV
, ^
), 等价(EQV
, =
, ==
)以及非(NOT
, ~
, !
),这些与逻辑代数和算术操作相一致。
目录 |
[编辑] Ada
Ada在标准包中定义Boolean
为一种枚举类型,有两种值False
和True
,并且False
< True
。
type Boolean is (False, True); p : Boolean := True; ... if p then ... end if;
相关的操作(=
, /=
, <
, <=
, >
, >=
)使用语所有的枚举类型,包括Boolean
。布尔运算and
, or
, xor
和not
由Boolean
及任意声明的子类型定义。布尔运算也适用于Boolean
值数组。
[编辑] Algol
Algol 60有Boolean
数据类型和相关的操作,定义在Algol 60报告中。这在ALGOL 68中被简化为bool
。[1]
ALGOL 68语言详细说明(177页)中关于布尔操作定义的原文:
10.2.2. 布尔操作数的运算
- op ∨ = (bool a, b) bool:( a | true | b );
- op ∧ = (bool a, b) bool: ( a | b | false );
- op ¬ = (bool a) bool: ( a | false | true );
- op = = (bool a, b) bool:( a∧b ) ∨ ( ¬b∧¬a );
- op ≠ = (bool a, b) bool: ¬(a=b);
- op abs = (bool a)int: ( a | 1 | 0 );
[编辑] C
在C99之前,C语言的标准没有提供布尔类型,但是这不意味着C90不能表示布尔值的概念。C中的所有布尔运算(&&, ||)以及条件声明(if, while)都以非零值代表真,零值代表假。这样,在其他类型如一个整数或一个枚举中保存布尔值就变得很平常。为了方便,常常为布尔类型创建一个typedef来和一些已存在的数据类型相关联。C99标准也提供了一个内置的布尔类型。
为了说明C中的布尔型,注意以下C代码:
if (my_variable) { printf("True!\n"); } else { printf("False!\n"); }
等价于:
if (my_variable != 0) { printf("True!\n"); } else { printf("False!\n"); }
简单来说这就是一个整数类型。由于C标准要求0
用在指针上下文中时要代表空指针,上面的概念也可以用来检查一个指针是否为空,虽然一些程序风格不建议这样用。这种情况同样适用于浮点值,当比较它们的时候要特别小新,因为它们通常包含四舍五入的结果。通常,整型用来包含布尔变量。
虽然为了测试一个变量的真假值时没必要来命名真或假,但是在给它们分配值的时候却是需要的。(一种方法是使用零值和一,这样做的好处是语言独立。)其他方法,enum
关键字允许在语言中根据你的选择来命名元素,例如:
typedef enum { FALSE, TRUE } boolean; ... boolean b;
如下典型的预处理宏经常被使用。
#define FALSE 0 #define TRUE 1 ... int f = FALSE;
有时TRUE
可能被定义为-1或~0(位运算0的补)。这意味着在现在常见的二补数计算机架构的整型中所有的位都被设置为1。
但是,在C中任意非零值都代表真就带来了问题,因为TRUE
由一个特定的值来表示,因此在其他语言中if (foo == TRUE) ...
只不过是多余的,而在C中,就是错误的代码。
[编辑] C99
C99中有bool
类型,取值为true
和false
,定义在<stdbool.h>
头文件中:
#include <stdbool.h> bool b = false; ... b = true;
[编辑] C++
C++编程语言在其标准化过程中引入了bool
、true
和false
关键字,增加了原生数据类型来支持布尔数据,其大小被实现定义。[2] bool
在1993年被引入。[3].
1998年的C++标准库定义了一个vector<bool>
类的特例。为了优化空间,其中的元素被打包,使得每一个布尔变量只使用一位内存。这被认为是一个错误。vector<bool>
不符合STL容器的需要。例如一个container<T>::reference
必须为T
类型的一个真值左值。这和vector<bool>
的情况不同。类似地,vector<bool>::iterator
在解除引用时不产生一个bool&
。在C++标准委员会和库工作组之间有个共识,就是vector<bool>
应该被反对或完全从下一个标准中被移除。[4][5]
[编辑] C#
在C#中,布尔变量通过保留字bool
来识别,这个保留字是预定义结构类型System.Boolean
的别名,占一字节。在bool
和其他类型之间不存在标准的转换。此语言还提供了一个布尔类型DBbool
,可以表示三种值:true
、false
和null
。这和SQL中布尔表达式的用法类似。[6]
输出一个布尔型的代码如下:
bool myBool = (i == 5); System.Console.WriteLine(myBool ? "I = 5" : "I != 5");
[编辑] Fortran
在Fortran被标准化之前,于1950年代引入了LOGICAL
关键字和相关的操作.NOT.
、.AND.
、.OR.
等等。
[编辑] Java
在Java语言中,布尔变量由原始类型boolean
表示。Java虚拟机将实际在内存中的表现抽象,这样JVM开发者可以使用尽可能方便的方式来代表布尔量(例如,一个字节或者一个字)。
Java语言规范不允许任何显式或隐式的从boolean
的转换。这样就需要编译器拒绝如下代码:
int i = 1; if (i) System.out.println("i is not zero."); else System.out.println("i is zero.");
因为整型变量i
不能转换为一个布尔型并且if
语句需要一个boolean
条件。[7]
在Java中,boolean
值(和其他原始类型相同)可以被附加到字符串。这个特性提供了一个默认的布尔型的可视化表现(true
被显示为"true",false
被显示为"false")。[7]
[编辑] JavaScript
JavaScript有两个关键字,true
和false
,两者都为小写。JavaScript是一种弱类型的语言,没有明确的布尔数据类型供其变量使用。但是许多值用在逻辑上下文时可以被当成false
,包括零、null
、零长度字符串以及对象的unknown
属性。所有其他变量值,包括空数组和空对象,都被认为是true
。这个语言的确提供了一个Boolean
对象,可以被用作控制布尔值的容包装。Boolean
对象总是被当成true
尽管其包含false
值。
var objBool = new Boolean(false); if ( false || 0 || "" || null || window.not_a_property ) { alert("never this"); } else if ( true && [] && {} && objBool ) { alert("Hello Wikipedia"); // 会弹出这个消息 }
[编辑] λ演算
[编辑] Lisp
LISP有两个特殊的符号T
和NIL
,分别代表了逻辑值真和假。但是,任意非NIL
值都由LISP系统翻译成真。特殊的符号NIL
也用空列表()
表示。因此空列表为假,但是任何有数据的列表都为真。这样,什么都没有为假,其他所有都为真。
[编辑] ML
和Ocaml类似,ML语言拥有bool
类型,包含true
和false
值,例如:
- fun isittrue x = if x then "YES" else "NO" ; > val isittrue = fn : bool -> string - isittrue true; > val it = "YES" : string - isittrue false; > val it = "NO" : string - isittrue (8=8); > val it = "YES" : string - isittrue (7=5); > val it = "NO" : string
[编辑] Objective-C
Objective-C提供了BOOL
类型,以及宏YES
和NO
。由于Objective-C是C语言的超集,因此C语言的布尔语义也适用。
[编辑] Ocaml
Ocaml has a bool
type that has true
and false
values.
# 1 = 1 ;; - : bool = true
Like other enumerated types, a value of this type uses a word of memory.
[编辑] Pascal
Boolean
Pascal提供的基本数据类型,定义和用法如下:
(* 系统或标准声明 *) Type Boolean = (False,True); (* 用法 *) var value: Boolean; ... value := True; value := False; if value then begin ... end;
注意,枚举外的值没有被定义。一些像Delphi这样的编译器为了接口目的拥有特殊的扩展布尔类型,映射到C数值类型上。(Delphi: bytebool,wordbool,longbool)
[编辑] Perl
In the Perl programming language, there is no distinction between numbers, strings and other non-aggregate data types. (They are all called "scalar".) Aggregate types without any elements, empty strings, numbers which equal a value of 0, the strings ""
and "0"
, and undefined variables evaluate to "false" when used in a Boolean context. All other values (including strings such as 0.0
and 0E0
which are "zero but true") evaluate to "true".
Elements of aggregates may also be tested against "existence" or "non-existence"[1], and all variables may be evaluated as either "defined" or "undefined".[2] (An element of a hash or array that has been assigned the value undef
exists but is undefined.) In Perl this distinction is important when evaluating scalars in a boolean manner to prevent "false falses" where one of the above values should be considered "true".
There are no built-in true or false constants in Perl 5, however the values do exist internally in Perl6.
1
is traditionally used for true, and constructs such as ... while 1
are special-cased to avoid advisory warnings. Internally, recent versions of Perl 5 have a variety of predefined yesses and nos, so that the recommended way to provide a false value has recently shifted from undef
to !1
.
[编辑] PHP
PHP has a boolean datatype [8] with two values: true and false (case doesn't matter).
$var = true; $var = false; print $var == true ? "T" : "F"; print $var === true ? "T" : "F"; print is_bool($var) ? "T" : "F"; print gettype($var);
Several values evaluate to a logical false [9] with the loose comparison operator ==
. There are generally empty instances of a type, or are considered equivalent to the number 0. These vales are:
- false
- zero
- "0"
- NULL
- empty array
- empty string
PHP programmers wishing to distinguish a boolean variable set to false from other types of variable must use the strict comparison operator ===
.
[编辑] Python
The Python programming language defines True and False values as its boolean type, as well as allowing all objects to be tested for their truth value. The following values are considered false:
- Numeric zero, None, False.
- Empty containers such as empty strings, lists, tuples, dicts and sets.
- User defined object instances have control over their boolean value through special methods
__nonzero__
[10] and__len__
.
In all other cases, objects are considered true.
Boolean operators and boolean built-in types always return one of the boolean values True and False except for the operators "or
" and "and
" which return one of their operands (from left to right, the first operand that determines the boolean value of the expression).[11]
>>> class spam: pass # spam is assigned a class object. ... >>> eggs = "eggs" # eggs is assigned a string object. >>> spam == eggs # (Note double equals sign for equality testing). False >>> spam != eggs # != and == always return bool values. True >>> spam and eggs # and returns an operand. 'eggs' >>> spam or eggs # or also returns an operand. <class __main__.spam at 0x01292660> >>>
[编辑] Ruby
The Ruby programming language does not have a Boolean data type as part of the language. Like many other interpreted languages, all variables are dynamically typed. Instead, ruby defines the explicit values of false
and nil
, and everything else is considered true
, including 0, [ ]
, and the empty string ""
. The values true
, false
, and nil
can be assigned to variables, returned from functions or methods, and compared in Boolean expressions.
a = 0 if (a) print "true" else print "false" end
will print "true", which might come as a surprise to a new user of the language.
Since Ruby is a pure object-oriented programming language, even the "explicitly" defined values of true
, false
and nil
are objects that each have their own class:
p false.class p true.class p nil.class
Would output "FalseClass", "TrueClass" and "NilClass" respectively.
[编辑] Scheme
Scheme has two special symbols #t
and #f
which represent the logical values of true and false respectively. However, any non-#f
value is interpreted as true. Note that unlike Lisp, nil
or '()
, the empty list, is separate from #f
in Scheme, and therefore is considered true.
[编辑] SQL
SQL supports three-valued logic (3VL), and comparison predicates in SQL can return any of three possible results: true, false, or unknown. The Boolean datatype was introduced in the ISO SQL:1999 standard, which specified that in addition to the three possible SQL Boolean values, instances of the datatype could be set to null[12]. For DBMSs that implement the ISO SQL:1999 standard, the following code creates a table which holds instances of the Boolean data type.
CREATE TABLE test1 ( a int, b BOOLEAN ); INSERT INTO test1 VALUES (1, true); INSERT INTO test1 VALUES (2, false); INSERT INTO test1 VALUES (3, NULL); -- The SQL:1999 standard says that vendors can use null in place of the -- SQL Boolean value unknown. It is left to the vendor to decide if -- null should be used to completely replace unknown. The standard also -- says that null should be treated as equivalent to unknown, which is an -- inconsistency. The following line may not work on all SQL:1999-compliant -- systems. INSERT INTO test1 VALUES (4, unknown); SELECT * FROM test1;
The SQL Boolean data type did not gain widespread adoption, owing to inconsistencies in the standard and lack of support from vendors. Most SQL DBMSs use other data types like bit, byte, and char to simulate the behavior of Boolean data types.
[编辑] Visual Basic
In Visual Basic Boolean values from comparisons can be stored in variables with the Boolean
data type, which is stored as a 16-bit signed integer, but should only have the values True(-1)
and False(0)
. For example:
Dim isSmall As Boolean isSmall = intMyNumber < 10 ' Expression evaluates to True or False If isSmall Then MsgBox("The number is small") End If Dim hellFreezesOver As Boolean ' Boolean variables are initialized as False hellFreezesOver = False ' Or you can use an assignment statement Do Call CheckAndProcessUserInput() Loop Until hellFreezesOver
Note: Although Boolean values should only be -1 or 0, other values can be coerced into them by calling a function with a Variant
ByRef
parameter. It is highly recommended that you do not do this.
Sub Voo(ByRef v As Variant) v = 1 End Sub Sub Bar(ByRef b As Boolean) b = 1 End Sub Dim b1 As Boolean, b2 As Boolean b1 = True b2 = True Debug.Print (b1 = b2) 'True Call Voo(b2) Debug.Print (b1 = b2) 'False Call Bar(b2) Debug.Print (b1 = b2) 'True
[编辑] XPath and XQuery
XML Path Language (XPath 2.0) and XML Query Language (XQuery 1.0) both rely on XML Schema for Boolean data type support. The XML Schema xs:boolean data type supports both true and false Boolean values. XPath and XQuery define a set of rules for calculating the effective Boolean value of expressions.
XPath 1.0 and languages based on it, like XML Stylesheet Language (XSL), also support Boolean data types and implicit calculation of effective Boolean values from non-Boolean expressions.
[编辑] See also
- true and false shell scripting commands
- Shannon's expansion
[编辑] Notes and references
- ^ Report on the Algorithmic Language ALGOL 68, Section 10.2.2.(1968年Aug月).
- ^ Working Paper for Draft Proposed International Standard for Information Systems-- Programming Language C++(1996年Dec月).
- ^ Evolving a language in and for the real world: C++ 1991-2006(2007年).
- ^ vector<bool>: More Problems, Better Solutions(1999年Aug月).
- ^ A Specification to deprecate vector<bool>(2007年Mar月).
- ^ C# Language Specifications, online at http://msdn.microsoft.com/en-us/library/aa664483(VS.71).aspx
- ^ 7.0 7.1 Java Language Specification, 3rd edition - online at http://java.sun.com/docs/books/jls/
- ^ PHP: Booleans - Manual
- ^ PHP: PHP type comparison tables - Manual
- ^ Special method names: Basic customization.Python Language Reference.
- ^ Boolean operations.
- ^ ISO/IEC. ISO/IEC 9075-1:1999 SQL Standard (pdf format). Section 4.4.3.3. 1999.