Discover

BOOLEAN DATATYPE

In computer science, the 'Boolean datatype', sometimes called the ''logical datatype'', is a primitive datatype having two values: ''one'' and ''zero'' (which are equivalent to 'true' and 'false'). It is the special case of a binary numeric datatype of only one digit, or bit, and can also be represented in any other radix by restricting the range of allowed values for certain operations.
This datatype is used in Boolean and other operations such as and (AND, &,
), or (OR, |, +), exclusive or/not equivalent (xor, NEQV, ^), equal (EQV, =, ==) and not (NOT, ~, !) which correspond to some of the operations of Boolean algebra and arithmetic.

Contents
Ada
Algol
C
C++
C#
Fortran
Java
Lambda calculus
Objective-C
Ocaml
Lisp
ML
Pascal
Perl
PHP
true ? "T" : "F";
print $var
Python
always return bool values.
True
>>> spam and eggs # and returns an operand.
'eggs'
>>> spam or eggs # or also returns an operand.

>>>
Visual Basic
Notes and references
See also

Ada


Ada defines Boolean in the package Standard as an enumerated type with values False and True where False < True.

type Boolean is (False, True);
p : Boolean := True;
...
if p then
...
end if;

The relational operators (=, /=, <, <=, >, >=) apply to all enumerated types, including Boolean. Boolean operators and, or, xor, and not are defined on Boolean and any declared subtype. The Boolean operators also apply to arrays of Boolean values.

Algol


Algol 60 had a Boolean datatype and associated operations, defined in the Algol 60 report. This was abbreviated to bool in ALGOL 68.[1]
An actual extract from the 'ALGOL 68' language specification (page 177) where the boolean operators are defined:
10.2.2. Operations on Boolean Operands

  1. 'op' ∨ = ('bool' a, b) 'bool':( a | 'true' | b );

  2. 'op' ∧ = ('bool' a, b) 'bool': ( a | b | 'false' );

  3. 'op' ¬ = ('bool' a) 'bool': ( a | 'false' | 'true' );

  4. 'op' = = ('bool' a, b) 'bool':( a∧b ) ∨ ( ¬b∧¬a );

  5. 'op' ≠ = ('bool' a, b) 'bool': ¬(a=b);

  6. 'op' 'abs' = ('bool' a)'int': ( a | 1 | 0 );


C


Prior to C99, the standards for the C programming language provided no Boolean type. This however does not mean that C cannot store boolean values, as in C nonzero values signify 'true' and zero values signify 'false'. Thus, it is common to store boolean values in variables of another type, such as an integer or an enum. For convenience, it is also common to create a typedef for a boolean type, which resolves to some existing datatype. The C99 standard also provides a built-in boolean type.
To illustrate booleans in C, note that the C code:

if (my_variable) {
printf("True!
");
} else {
printf("False!
");
}

is equivalent to:

if (my_variable != 0) {
printf("True!
");
} else {
printf("False!
");
}

This is straightforward for integer datatypes. Since C standards require that a null pointer be represented as 0, it can also be used to check a pointer for NULL, although some code styles discourage this use. Binary floating-point values are approximations of displayed decimal values and so should not normally be compared for equality. Traditionally, integers are used to contain boolean variables.
While it is not necessary to name the true and false values in order to test variables for truth or falsehood, it is necessary to do so in order to assign values to them. (One way is to use the values zero and one, which have the advantage of being language-independent.) Alternatively, the enum keyword allows for naming elements in the language of your choice, for example:

typedef enum _boolean { FALSE, TRUE } boolean;
...
boolean b;

The following typical preprocessor macros are also often used.

#define FALSE 0
#define TRUE 1
...
int f = FALSE;

Sometimes TRUE may be defined as -1 or ~0 (the bitwise complement of zero). This means that all bits of the integer are set to 1.
However, any non-zero value represents true in C. So while in other languages, if (foo == TRUE) ... is merely redundant, in C, it is actually ''incorrect'' code.
On a recent C compiler (supporting the C99 standard), there is a _Bool type, which is used to define bool by the <stdbool.h> header:

#include
bool b = false;
...
b = true;

C++


During its standardization process, the C++ programming language introduced the bool, true and false keywords, adding a native datatype to support boolean data. Its size is implementation defined.[2]
Preprocessor macros may be used to turn bool into _Bool, false into 0 and true into 1, allowing compatibility with the aforementioned C99 use of the stdbool.h header.[3]
The 1998 C++ Standard Library defines a specialization of the vector class. To optimize space, the elements are packed so that every bool only uses one bit of memory. This is widely considered a mistake. vector does not meet the requirements for a STL container. For instance, a container::reference must be a true lvalue of type T. This is not the case with vector. Similarly, the vector::iterator does not yield a bool& when dereferenced. There is a general consensus among the C++ Standard Committee and the Library Working Group that vector should be deprecated or entirely removed from the next version of the standard.[4][5]

C#


In C#, Boolean variables are identified through the reserved word bool, which is an alias for the predefined struct type System.Boolean. It occupies one byte. No standard conversions exist between bool and other types. The language also provides a boolean type bool? that can represent three values: true, false, and null. This is similar to the type used for boolean expressions in SQL[6]
Code to output a Boolean could be represented like this:

bool myBool = (i == 5);
System.Console.WriteLine(myBool ? "I = 5" : "I != 5");

Fortran


The LOGICAL keyword and associated operations .NOT., .AND., .OR., etc. were introduced in the 1950s, before Fortran was standardized.

Java


In the Java programming language, boolean variables are represented by the primitive type boolean. The Java Virtual Machine (JVM) abstracts away from the actual representation in memory, so JVM writers can represent booleans in whatever manner is convenient (for example, one byte, or one word).
The Java Language Specification does not permit any explicit or implicit casts to or from boolean. Thus, it requires the compiler to reject this code:

int i = 1;
if (i)
System.out.println("i is not zero.");
else
System.out.println("i is zero.");

because the integer variable i cannot be cast to a boolean, and the if statement requires a boolean condition.[7]
In Java, boolean values (like other primitive types) can be appended to Strings. This feature provides a default visual representation of a boolean (true is displayed as "true" and false as "false").

Lambda calculus


In the lambda calculus formal model of computing, booleans are represented as Church booleans.

Objective-C


Objective-C provides a type BOOL, and macros YES and NO. Since Objective-C is a superset of C, C language semantics for booleans also apply.

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.

Lisp


Lisp has two special symbols T and NIL which represent the logical values of true and false respectively. However, any non-NIL value is interpreted by a LISP system as true. The special symbol NIL is also represented by (), the empty list. So the empty list is false, but any list with data has the logical value of true. Therefore "nothing" is false and everything else is true.

ML


Like Ocaml, ML has a bool type that has true and false values. For example:

- 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

Pascal


Boolean is a basic datatype provided by Pascal. Its definition and uses:

var
value: Boolean;
...
value := True;
value := False;
if value then
begin
...
end;

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



$var = true;
$var = false;
print $var

true ? "T" : "F";
print $var

= true ? "T" : "F";
print is_bool($var) ? "T" : "F";
print gettype($var);

Python


The Python programming language defines True and False values as its bool 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__[8] and __len__.
In all other cases, objects are considered true.
Boolean operators and boolean built-in types always return one of the bool 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).[9]

>>> 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.

>>>

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.

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")
Endif
Dim hellFreezesOver As Boolean ' Boolean variables are initialized as False
hellFreezesOver = False ' Or you can use an assignment statement
Do Until hellFreezesOver
Call CheckAndProcessUserInput()
Loop

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

Notes and references


1. Report on the Algorithmic Language ALGOL 68, Section 10.2.2.
2. Working Paper for Draft Proposed International Standard for Information Systems-- Programming Language C++
3. Dinkum Compleat Libraries Reference
4. vector: More Problems, Better Solutions
5. A Specification to deprecate vector
6. ''C# Language Specifications'', online at http://msdn.microsoft.com/vcsharp/programming/language/default.aspx
7. ''Java Language Specification'', 3rd edition - online at http://java.sun.com/docs/books/jls/
8. Special method names: Basic customization
9. Boolean operations

See also



true and false shell scripting commands

This article provided by Wikipedia. To edit the contents of this article, click here for original source.

psst.. try this: add to faves