Boolean values: Difference between revisions

From Rosetta Code
Content added Content deleted
imported>Tromp
 
(46 intermediate revisions by 26 users not shown)
Line 1: Line 1:
{{task|Basic language learning}}
[[Category:Simple]]
[[Category:Simple]]
{{task|Basic language learning}}


;Task:
;Task:
Line 11: Line 11:
*   [[Logical operations]]
*   [[Logical operations]]
<br><br>
<br><br>
=={{header|8th}}==

In 8th, any non-zero number is true, as is the specific boolean value 'true'. Everything else evaluates as 'false' (including the boolean value, 'false')
=={{header|11l}}==
=={{header|11l}}==
11l defines a built-in data type <code>Bool</code>, which has two values represented by the constants <code>0B</code> and <code>1B</code>.
11l defines a built-in data type <code>Bool</code>, which has two values represented by the constants <code>0B</code> and <code>1B</code>.

=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
The are no TRUE or FALSE constants in 360 Assembly; but an often used convention is :
The are no TRUE or FALSE constants in 360 Assembly; but an often used convention is :
<lang 360asm>FALSE DC X'00'
<syntaxhighlight lang="360asm">FALSE DC X'00'
TRUE DC X'FF'</lang>
TRUE DC X'FF'</syntaxhighlight>
=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
There are no built-in true or false constants, but the functionality can be easily replicated with zero or nonzero values (or any two values which can cause a mutually exclusive branch condition, such as with <code>#$7f</code> and <code>#$80</code> and using <code>BMI</code>/<code>BPL</code>)
There are no built-in true or false constants, but the functionality can be easily replicated with zero or nonzero values (or any two values which can cause a mutually exclusive branch condition, such as with <code>#$7f</code> and <code>#$80</code> and using <code>BMI</code>/<code>BPL</code>)
Line 24: Line 24:
A single bit represents true or false. By convention, 0 (cleared) is false, 1 (set) is true.
A single bit represents true or false. By convention, 0 (cleared) is false, 1 (set) is true.
In the following, "bit" represents the direct address of any of the 256 directly accessible bits.
In the following, "bit" represents the direct address of any of the 256 directly accessible bits.
<lang asm>clr bit ; clears
<syntaxhighlight lang="asm">clr bit ; clears
setb bit ; sets</lang>
setb bit ; sets</syntaxhighlight>
=={{header|68000 Assembly}}==

There are no built-in true or false constants, but the functionality can be easily replicated with zero or nonzero values (or any two values which can cause a mutually exclusive branch condition, such as with <code>#$7f</code> and <code>#$80</code> and using <code>BMI</code>/<code>BPL</code>)
=={{header|8th}}==
In 8th, any non-zero number is true, as is the specific boolean value 'true'. Everything else evaluates as 'false' (including the boolean value, 'false')

=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program boolean.s */
/* program boolean.s */
Line 83: Line 81:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>

=={{header|ACL2}}==
=={{header|ACL2}}==
Same as [[Common Lisp|Boolean Values#Common Lisp]].
Same as [[Common Lisp|Boolean Values#Common Lisp]].
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Test(BYTE v)
PrintF("Variable v has value %B%E",v)
IF v THEN
PrintE("Condition IF v is satisfied.")
ELSE
PrintE("Condition IF v is not satisfied.")
FI
IF v=0 THEN
PrintE("Condition IF v=0 is satisfied.")
ELSE
PrintE("Condition IF v=0 is not satisfied.")
FI
IF v<>0 THEN
PrintE("Condition IF v<>0 is satisfied.")
ELSE
PrintE("Condition IF v<>0 is not satisfied.")
FI
IF v#0 THEN
PrintE("Condition IF v#0 is satisfied.")
ELSE
PrintE("Condition IF v#0 is not satisfied.")
FI
PutE()
RETURN


PROC Main()
Test(0)
Test(1)
Test(86)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Boolean_values.png Screenshot from Atari 8-bit computer]
<pre>
Variable v has value 0
Condition IF v is not satisfied.
Condition IF v=0 is satisfied.
Condition IF v<>0 is not satisfied.
Condition IF v#0 is not satisfied.

Variable v has value 1
Condition IF v is satisfied.
Condition IF v=0 is not satisfied.
Condition IF v<>0 is satisfied.
Condition IF v#0 is satisfied.

Variable v has value 86
Condition IF v is satisfied.
Condition IF v=0 is not satisfied.
Condition IF v<>0 is satisfied.
Condition IF v#0 is satisfied.
</pre>
=={{header|Ada}}==
=={{header|Ada}}==
[[Ada]] has a predefined discrete type with the specification:
[[Ada]] has a predefined discrete type with the specification:
<lang Ada> type Boolean is (False, True);</lang>
<syntaxhighlight lang="ada"> type Boolean is (False, True);</syntaxhighlight>
with Boolean lattice and relational operations defined on it. See [http://www.adaic.org/standards/1zrm/html/RM-A-1.html RM A.1].
with Boolean lattice and relational operations defined on it. See [http://www.adaic.org/standards/1zrm/html/RM-A-1.html RM A.1].

=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{trans|python}}
{{trans|python}}
Line 101: Line 148:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - note: null char is missing, AND the C generated is won't compile, so some conversions are missing from RS}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - note: null char is missing, AND the C generated is won't compile, so some conversions are missing from RS}}
ALGOL 68 Enforces strong typing and so has few default coercions. The appropriate operators must be used to convert to and from '''bool'''[ean] and the following code demonstrates principle conversions:
ALGOL 68 Enforces strong typing and so has few default coercions. The appropriate operators must be used to convert to and from '''bool'''[ean] and the following code demonstrates principle conversions:
<lang algol68>BOOL f = FALSE, t = TRUE;
<syntaxhighlight lang="algol68">BOOL f = FALSE, t = TRUE;
[]BOOL ft = (f, t);
[]BOOL ft = (f, t);
STRING or = " or ";
STRING or = " or ";
Line 130: Line 177:
print(("string: """, string , """ => ", string /= "", or, UPB string /= 0, new line));
print(("string: """, string , """ => ", string /= "", or, UPB string /= 0, new line));
print((new line))
print((new line))
OD</lang>
OD</syntaxhighlight>


{{out}}
{{out}}
Line 158: Line 205:
</pre>
</pre>
Note: The '''string''' '''repr'''[esentation] of '''false''' and '''true''' are defined by the variables ''flop'' and ''flip'' respectively.
Note: The '''string''' '''repr'''[esentation] of '''false''' and '''true''' are defined by the variables ''flop'' and ''flip'' respectively.

=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
The boolean type is called logical in Algol W - the values are represented by the keywords true and false. Numbers, strings etc. cannot be used where logical values are required.
The boolean type is called logical in Algol W - the values are represented by the keywords true and false. Numbers, strings etc. cannot be used where logical values are required.

=={{header|APL}}==
=={{header|APL}}==
0 and 1 are used for boolean types in APL (as in J below).
0 and 1 are used for boolean types in APL (as in J below).
<syntaxhighlight lang="apl">
<lang APL>
1 ^ 1
1 ^ 1
1
1
1 ^ 0
1 ^ 0
0
0
</syntaxhighlight>
</lang>

=={{header|AppleScript}}==
=={{header|AppleScript}}==
AppleScript has built-in boolean keywords <code>true</code> and <code>false</code>. Numbers do not work in place of boolean expressions, but they do coerce to and from.
AppleScript has built-in boolean keywords <code>true</code> and <code>false</code>. Numbers do not work in place of boolean expressions, but they do coerce to and from.


<lang AppleScript>1 > 2 --> false
<syntaxhighlight lang="applescript">1 > 2 --> false
not false --> true
not false --> true


Line 180: Line 224:
--> {1, 0, true, false}
--> {1, 0, true, false}


true = 1 --> false</lang>
true = 1 --> false</syntaxhighlight>


AppleScript also has constants <code>yes</code> and <code>no</code>, which coerce easily to boolean values. They have little practical value in AppleScript except if one wishes to use them as arguments in place of boolean values for novelty's sake. They are interchangeable with boolean values as parameters in AppleScriptObjC (not demonstrated here).
AppleScript also has constants <code>yes</code> and <code>no</code>, which coerce easily to boolean values. They have little practical value in AppleScript except if one wishes to use them as arguments in place of boolean values for novelty's sake. They are interchangeable with boolean values as parameters in AppleScriptObjC (not demonstrated here).


<lang AppleScript>{yes as boolean, no as boolean}
<syntaxhighlight lang="applescript">{yes as boolean, no as boolean}
--> {true, false}</lang>
--> {true, false}</syntaxhighlight>


<code>yes</code> and <code>no</code> do not coerce to integer values.
<code>yes</code> and <code>no</code> do not coerce to integer values.
Line 191: Line 235:
Finally, AppleScript also includes keywords <code>with</code> and <code>without</code>, used in declaring parameters for and sending parameters of boolean nature to handlers. They are synonymous with <code>true</code> and <code>false</code>, respectively, and the compiler will sometimes perform the substitution at compile time.
Finally, AppleScript also includes keywords <code>with</code> and <code>without</code>, used in declaring parameters for and sending parameters of boolean nature to handlers. They are synonymous with <code>true</code> and <code>false</code>, respectively, and the compiler will sometimes perform the substitution at compile time.


<lang AppleScript>sortItems from L given reversal : true</lang>
<syntaxhighlight lang="applescript">sortItems from L given reversal : true</syntaxhighlight>


gets compiled immediately to become:
gets compiled immediately to become:


<lang AppleScript>sortItems from L with reversal</lang>
<syntaxhighlight lang="applescript">sortItems from L with reversal</syntaxhighlight>


However, the equivalent call to the handler utilising <code>yes</code>, whilst accepted readily in place of its boolean counterpart, is left alone by the compiler:
However, the equivalent call to the handler utilising <code>yes</code>, whilst accepted readily in place of its boolean counterpart, is left alone by the compiler:


<lang AppleScript>sortItems from L given reversal:yes</lang>
<syntaxhighlight lang="applescript">sortItems from L given reversal:yes</syntaxhighlight>

=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program areaString.s */
/* program areaString.s */
Line 270: Line 313:




</syntaxhighlight>
</lang>

=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>a: true
<syntaxhighlight lang="rebol">a: true
b: false
b: false


Line 279: Line 321:


if? b -> print "nope"
if? b -> print "nope"
else -> print "yep"</lang>
else -> print "yep"</syntaxhighlight>
{{out}}
{{out}}
Line 285: Line 327:
<pre>yep
<pre>yep
yep</pre>
yep</pre>

=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
When an expression is required to evaluate to true or false (such as an <code>IF</code>-statement), a blank or zero result is considered false and all other results are considered true. Operators such as <code>NOT</code>/<code>AND</code>/<code>OR</code>/<code>></code>/<code>=</code>/<code><</code> automatically produce a true or false value: they yield 1 for true and 0 for false. A variable can be used to hold a false value simply by making it blank or assigning 0 to it. The words 'true' and 'false' are built-in variables containing 1 and 0. They can be used to make a script more readable.
When an expression is required to evaluate to true or false (such as an <code>IF</code>-statement), a blank or zero result is considered false and all other results are considered true. Operators such as <code>NOT</code>/<code>AND</code>/<code>OR</code>/<code>></code>/<code>=</code>/<code><</code> automatically produce a true or false value: they yield 1 for true and 0 for false. A variable can be used to hold a false value simply by making it blank or assigning 0 to it. The words 'true' and 'false' are built-in variables containing 1 and 0. They can be used to make a script more readable.

=={{header|Avail}}==
=={{header|Avail}}==


While Avail has many methods for handling booleans, <code>boolean</code> itself is simply an enumeration type of the atoms <code>true</code> and <code>false</code>. This enumeration and these atoms are only special ''by convention'' of being used for the logical operations provided by the standard library. It would be perfectly possible to define an entirely new boolean system with new types and atoms (or values).
While Avail has many methods for handling booleans, <code>boolean</code> itself is simply an enumeration type of the atoms <code>true</code> and <code>false</code>. This enumeration and these atoms are only special ''by convention'' of being used for the logical operations provided by the standard library. It would be perfectly possible to define an entirely new boolean system with new types and atoms (or values).

=={{header|AWK}}==
=={{header|AWK}}==


Line 301: Line 340:
In the following example we use zero for false, and one for true to assign boolean values. However, this is just a convention, so other values may also have been used:
In the following example we use zero for false, and one for true to assign boolean values. However, this is just a convention, so other values may also have been used:


<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
# Do not put quotes round the numeric values, or the tests will fail
# Do not put quotes round the numeric values, or the tests will fail
a = 1 # True
a = 1 # True
Line 318: Line 357:
if (b != 0) { print "eighth test b is true" } # This should not print
if (b != 0) { print "eighth test b is true" } # This should not print


}</lang>
}</syntaxhighlight>

=={{header|Axe}}==
=={{header|Axe}}==
In Axe, there are no keywords for true and false. Any expression that evaluates to zero is considered false, and any expression that evaluates to non-zero is considered true. Unlike other languages, there is no canonical value for true (e.g. 1).
In Axe, there are no keywords for true and false. Any expression that evaluates to zero is considered false, and any expression that evaluates to non-zero is considered true. Unlike other languages, there is no canonical value for true (e.g. 1).

=={{header|BASIC}}==
=={{header|BASIC}}==
Most BASICs have no keywords for true and false. Boolean expressions evaluate to 0 when false, and a non-zero value (traditional versions of basic use a value of one, although some variants use a value of negative one) when true. Numbers also work in place of boolean expressions following those rules.
Most BASICs have no keywords for true and false. Boolean expressions evaluate to 0 when false, and a non-zero value (traditional versions of basic use a value of one, although some variants use a value of negative one) when true. Numbers also work in place of boolean expressions following those rules.


<lang gwbasic>10 LET A%=0
<syntaxhighlight lang="basic">10 LET A%=0
20 LET B%=NOT(A%)
20 LET B%=NOT(A%)
30 PRINT "THIS VERSION OF BASIC USES"
30 PRINT "THIS VERSION OF BASIC USES"
Line 336: Line 373:
90 IF A%<>0 THEN PRINT "TEST FIVE (TRUE BY COMPARISON) DOES NOT PRINT"
90 IF A%<>0 THEN PRINT "TEST FIVE (TRUE BY COMPARISON) DOES NOT PRINT"
100 IF B%<>0 THEN PRINT "TEST SIX (TRUE BY COMPARISON) DOES PRINT"
100 IF B%<>0 THEN PRINT "TEST SIX (TRUE BY COMPARISON) DOES PRINT"
110 END</lang>
110 END</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
IF statement condition treats any non-zero numeric value as true. Comparison operators evaluate to 1 (true) or 0 (false).
IF statement condition treats any non-zero numeric value as true. Comparison operators evaluate to 1 (true) or 0 (false).
Examples:<lang ApplesoftBASIC>? 2 = 3
Examples:<syntaxhighlight lang="basic">? 2 = 3
? 2 = 2
? 2 = 2
IF 7 THEN ?"HELLO"</lang>
IF 7 THEN ?"HELLO"</syntaxhighlight>


{{out}}
{{out}}
Line 350: Line 387:


==={{header|BaCon}}===
==={{header|BaCon}}===
<lang qbasic>' Boolean TRUE and FALSE are non-zero and zero constants
<syntaxhighlight lang="basic">' Boolean TRUE and FALSE are non-zero and zero constants
a = TRUE
a = TRUE
b = FALSE
b = FALSE
Line 357: Line 394:
IF 0 THEN PRINT "TRUE" : ELSE PRINT "FALSE"
IF 0 THEN PRINT "TRUE" : ELSE PRINT "FALSE"
IF 1 THEN PRINT "TRUE"
IF 1 THEN PRINT "TRUE"
IF 2 THEN PRINT "TRUE"</lang>
IF 2 THEN PRINT "TRUE"</syntaxhighlight>


{{out}}
{{out}}
Line 373: Line 410:


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<syntaxhighlight lang="basic">
<lang basic256>
' BASIC256 used numbers to represent true and false
' BASIC256 used numbers to represent true and false
' values. Zero is false and anything else is true.
' values. Zero is false and anything else is true.
Line 381: Line 418:
print false
print false
print true
print true
</syntaxhighlight>
</lang>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbcbasic> REM BBC BASIC uses integers to represent Booleans; the keywords
<syntaxhighlight lang="basic"> REM BBC BASIC uses integers to represent Booleans; the keywords
REM FALSE and TRUE equate to 0 and -1 (&FFFFFFFF) respectively:
REM FALSE and TRUE equate to 0 and -1 (&FFFFFFFF) respectively:
PRINT FALSE
PRINT FALSE
PRINT TRUE</lang>
PRINT TRUE</syntaxhighlight>

==={{header|Cherrycake}}===
The boolean value of true in Cherrycake is represented with a 'true' keyword, and the boolean value of false in Cherrycake is represented with a 'false' keyword. Booleans can also be represented with other types, such as binary and integers. In binary types, 0x01 and 0b01 represent true, and 0x00 and 0b00 represent false. In integer types, 1 represents true and 0 represents false.


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
Commodore BASIC evaluates any non-zero number for TRUE&mdash;but is typically represented as 16-bit signed integer value of -1 or $FFFF&mdash;and zero evaluates to FALSE.
Commodore BASIC evaluates any non-zero number for TRUE&mdash;but is typically represented as 16-bit signed integer value of -1 or $FFFF&mdash;and zero evaluates to FALSE.


<lang gwbasic>10 f%=("z"="a") : t%=not f% : rem capture a boolean evaluation
<syntaxhighlight lang="basic">10 f%=("z"="a") : t%=not f% : rem capture a boolean evaluation
15 print chr$(147);chr$(14);
15 print chr$(147);chr$(14);
20 print "True is evaulated as:";t%
20 print "True is evaulated as:";t%
Line 403: Line 443:
80 if i then print "True":goto 100
80 if i then print "True":goto 100
90 print "False"
90 print "False"
100 next</lang>
100 next</syntaxhighlight>


{{out}}
{{out}}
Line 436: Line 476:


Sample code:
Sample code:
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="basic">' FB 1.05.0 Win64


Dim i As Integer = 23
Dim i As Integer = 23
Line 449: Line 489:
i = CInt(true)
i = CInt(true)
Print i
Print i
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 465: Line 505:
==={{header|Microsoft Small Basic}}===
==={{header|Microsoft Small Basic}}===
Microsoft Small Basic has two constants: <code>"True"</code> and <code>"False"</code>.<br>
Microsoft Small Basic has two constants: <code>"True"</code> and <code>"False"</code>.<br>
<lang smallbasic>If c Then
<syntaxhighlight lang="basic">If c Then
notc = "False"
notc = "False"
Else
Else
notc = "True"
notc = "True"
EndIf</lang>
EndIf</syntaxhighlight>


==={{header|PowerBASIC}}===
==={{header|PowerBASIC}}===
Line 475: Line 515:
In addition to what's noted above under [[#BASIC|BASIC]], [[PowerBASIC for Windows]] and [[PowerBASIC Console Compiler]] have the <code>ISTRUE</code> and <code>ISFALSE</code> functions. According to the help file, they "return the logical truth or falsity of a given expression". ([[PowerBASIC]] lacks a boolean data type, so the usual practice is to use integers in [[PB/DOS]], and longs in [[PB/CC]] and [[PB/Win]].)
In addition to what's noted above under [[#BASIC|BASIC]], [[PowerBASIC for Windows]] and [[PowerBASIC Console Compiler]] have the <code>ISTRUE</code> and <code>ISFALSE</code> functions. According to the help file, they "return the logical truth or falsity of a given expression". ([[PowerBASIC]] lacks a boolean data type, so the usual practice is to use integers in [[PB/DOS]], and longs in [[PB/CC]] and [[PB/Win]].)


<lang powerbasic>DIM x AS LONG
<syntaxhighlight lang="basic">DIM x AS LONG
x = ISTRUE(1 = 1) ' returns -1
x = ISTRUE(1 = 1) ' returns -1
x = ISTRUE(1 = 0) ' returns 0
x = ISTRUE(1 = 0) ' returns 0
x = ISFALSE(1 = 1) ' returns 0
x = ISFALSE(1 = 1) ' returns 0
x = ISFALSE(1 = 0) ' returns -1</lang>
x = ISFALSE(1 = 0) ' returns -1</syntaxhighlight>


==={{header|PureBasic}}===
==={{header|PureBasic}}===
Line 487: Line 527:
QBasic, QuickBASIC, VB-DOS and GW-BASIC doesn't have a Boolean type. What it does is to take 0 as False, and any other value as True. The easiest way in QBASIC, QuickBASIC and VB-DOS is to create False and True constants of type Integer and, then, use them as needed:
QBasic, QuickBASIC, VB-DOS and GW-BASIC doesn't have a Boolean type. What it does is to take 0 as False, and any other value as True. The easiest way in QBASIC, QuickBASIC and VB-DOS is to create False and True constants of type Integer and, then, use them as needed:


<syntaxhighlight lang="basic">
<lang QBASIC>
CONST FALSE=0
CONST FALSE=0
CONST TRUE = Not FALSE
CONST TRUE = Not FALSE
Print FALSE
Print FALSE
Print TRUE
Print TRUE
</syntaxhighlight>
</Lang>


In GW-BASIC you can create a variable called FALSE% and other called TRUE% and do the same. Nevertheless, is more sure to create functions in order to avoid the value to be manipulated:
In GW-BASIC you can create a variable called FALSE% and other called TRUE% and do the same. Nevertheless, is more sure to create functions in order to avoid the value to be manipulated:


<syntaxhighlight lang="basic">
<lang QBASIC>
10 DEF FNFALSE = 0
10 DEF FNFALSE = 0
20 DEF FNTRUE = NOT FNFALSE
20 DEF FNTRUE = NOT FNFALSE
30 Print FNFALSE
30 Print FNFALSE
40 Print NFTRUE
40 Print NFTRUE
</syntaxhighlight>
</Lang>


==={{header|Run BASIC}}===
==={{header|Run BASIC}}===
Basically 0 is false and 1 is true
Basically 0 is false and 1 is true
<lang runbasic>if 1 then print "1 is true"
<syntaxhighlight lang="basic">if 1 then print "1 is true"
if not(0) then print "0 is false"
if not(0) then print "0 is false"
if 1 < 2 then print "1 < 2 TRUE"
if 1 < 2 then print "1 < 2 TRUE"
if 2 > 1 then print "2 > 1 TRUE"
if 2 > 1 then print "2 > 1 TRUE"
if not(2 < 1) then print "2 not < 1"
if not(2 < 1) then print "2 not < 1"
if not(1 = 0) then print "1 not = 0"</lang>
if not(1 = 0) then print "1 not = 0"</syntaxhighlight>

==={{header|SmallBASIC}}===
<syntaxhighlight lang="basic">
a = true
b = false
</syntaxhighlight>


==={{header|smart BASIC}}===
==={{header|smart BASIC}}===
Line 523: Line 569:


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang basic>
<syntaxhighlight lang="basic">
!True BASIC maneja correctamente las expresiones booleanas,
!True BASIC maneja correctamente las expresiones booleanas,
!Pero no tiene un tipo booleano.
!Pero no tiene un tipo booleano.
Line 539: Line 585:


END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 550: Line 596:
==={{header|uBasic/4tH}}===
==={{header|uBasic/4tH}}===
In conditionals, zero is false, non-zero is true. Note that '''=''' is not only used for assignment, it is also a fully qualified logical operator, so it is easy to assign a true boolean to a variable.
In conditionals, zero is false, non-zero is true. Note that '''=''' is not only used for assignment, it is also a fully qualified logical operator, so it is easy to assign a true boolean to a variable.
<lang>t = 1 = 1
<syntaxhighlight lang="basic">t = 1 = 1
f = 0 = 1
f = 0 = 1


Print "False = ";f;", True = ";t</lang>
Print "False = ";f;", True = ";t</syntaxhighlight>
{{out}}
{{out}}
<pre>False = 0, True = 1
<pre>False = 0, True = 1
Line 560: Line 606:


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<syntaxhighlight lang="basic">
<lang Yabasic>
// Yabasic usa números para representar los valores true y false
// Yabasic usa números para representar los valores true y false
// Las constantes incorporadas true y false representan uno y cero respectivamente.
// Las constantes incorporadas true y false representan uno y cero respectivamente.
Line 570: Line 616:
print true
print true
end
end
</syntaxhighlight>
</lang>


==={{header|Visual Basic}}===
==={{header|Visual Basic}}===
Line 576: Line 622:
<br>When converting an integer to a boolean, <code>0</code> is <code>False</code> and anything not equal to <code>0</code> is
<br>When converting an integer to a boolean, <code>0</code> is <code>False</code> and anything not equal to <code>0</code> is


<lang vb>Dim x As Boolean
<syntaxhighlight lang="basic">Dim x As Boolean
x = IIf(Int(Rnd * 2), True, False)
x = IIf(Int(Rnd * 2), True, False)
MsgBox x</lang>
MsgBox x</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
Line 586: Line 632:
You can make a variable false by clearing its value <code>set "var="</code>.
You can make a variable false by clearing its value <code>set "var="</code>.


<lang dos>
<syntaxhighlight lang="dos">
@echo off
@echo off


Line 606: Line 652:


pause>nul
pause>nul
</syntaxhighlight>
</lang>


'''Output:'''
'''Output:'''
Line 613: Line 659:
b is false
b is false
</pre>
</pre>

=={{header|bc}}==
=={{header|bc}}==
POSIX bc doesn't define Boolean values (i.e. it's up to the programmer which values represent false and true).
POSIX bc doesn't define Boolean values (i.e. it's up to the programmer which values represent false and true).


In GNU bc, 0 is false and any other value is true (but the result of a boolean expression will always be 1 if it is true).
In GNU bc, 0 is false and any other value is true (but the result of a boolean expression will always be 1 if it is true).

=={{header|Befunge}}==
=={{header|Befunge}}==
Zero is false, non-zero is true. This is only used by the horizontal and vertical switch operators (<code>_</code> and <code>|</code>).
Zero is false, non-zero is true. This is only used by the horizontal and vertical switch operators (<code>_</code> and <code>|</code>).

=={{header|Binary Lambda Calculus}}==

The standard representations for the booleans in lambda calculus are true = \then. \else. then, false = \then. \else. else, which correspond to BLC programs <code>00 00 110</code> and <code>00 00 10</code>.


=={{header|BQN}}==
=={{header|BQN}}==
Line 638: Line 686:
!0
!0
ERROR</pre>
ERROR</pre>

=={{header|Bracmat}}==
=={{header|Bracmat}}==
Bracmat operates with success and failure instead of true and false. Success and failure play the same role as true and false in conditional tests, but they are not values like true and false. Instead, success and failure are properties of expressions in addition to values. The simplest failing expression is the atomic expression <code>~</code>. The simplest succeeding atomic expression is the empty string <code>""</code> (or <code>()</code>). A slightly more complex failing expression is <code>1+1:3</code>, which postulates that <code>3</code> matches the result of adding <code>1</code> and <code>1</code>, while <code>1+1:2</code> of course succeeds.
Bracmat operates with success and failure instead of true and false. Success and failure play the same role as true and false in conditional tests, but they are not values like true and false. Instead, success and failure are properties of expressions in addition to values. The simplest failing expression is the atomic expression <code>~</code>. The simplest succeeding atomic expression is the empty string <code>""</code> (or <code>()</code>). A slightly more complex failing expression is <code>1+1:3</code>, which postulates that <code>3</code> matches the result of adding <code>1</code> and <code>1</code>, while <code>1+1:2</code> of course succeeds.

=={{header|Brainf***}}==
=={{header|Brainf***}}==
Zero is false, non-zero is true. This is only used by the loop brackets (<code>[</code> and <code>]</code>).
Zero is false, non-zero is true. This is only used by the loop brackets (<code>[</code> and <code>]</code>).

=={{header|C}}==
=={{header|C}}==
In C, a value which is equal to 0 is false, while a value which is not equal to 0 is true. Relational and logical operators evaluate to 0 for false and 1 for true. Any of the following can be used:
In C, a value which is equal to 0 is false, while a value which is not equal to 0 is true. Relational and logical operators evaluate to 0 for false and 1 for true. Any of the following can be used:
Line 653: Line 698:
* in C99, the boolean type <code>bool</code> (defined in header <tt><stdbool.h></tt>), where <code>true</code> gives true and <code>false</code> gives false
* in C99, the boolean type <code>bool</code> (defined in header <tt><stdbool.h></tt>), where <code>true</code> gives true and <code>false</code> gives false
* in C99, any [[Complex numbers|complex number]] type, where 0 (0 real and 0 imaginary) gives false, anything else gives true
* in C99, any [[Complex numbers|complex number]] type, where 0 (0 real and 0 imaginary) gives false, anything else gives true

=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
In C#, there are the reserved keywords <code>true</code> and <code>false</code>. Variables to hold these values are declared as either <code>bool</code> or <code>Boolean</code>. These types are identical, as <code>bool</code> is just shortand for <code>Boolean</code>. The collection type <code>BitArray</code> returns its values as <code>Boolean</code>, packing 8 values into each byte (In contrast, the <code>Boolean</code> type uses the entire byte for one value).
In C#, there are the reserved keywords <code>true</code> and <code>false</code>. Variables to hold these values are declared as either <code>bool</code> or <code>Boolean</code>. These types are identical, as <code>bool</code> is just shorthand for <code>Boolean</code>. The collection type <code>BitArray</code> returns its values as <code>Boolean</code>, packing 8 values into each byte (In contrast, the <code>Boolean</code> type uses the entire byte for one value).


In C# 8.0 nullable type was introduced and when applied to <code>bool</code> supports all values and an additional <code>null</code> value and useful for some applications where the value can be undefined or missing.
There is also the <code>Nullable<T></code> type that represents all values of its underlying value type <code>T</code> and an additional <code>null</code> value. It has a shorthand notation: <code>T?</code> (When <code>T</code> is a reference type, <code>T?</code> means something else. It is not a different type, but just a hint to the compiler.)
So, when applied to <code>bool</code>, we have a <code>bool?</code> type that supports 3 values: <code>true</code>, <code>false</code> and <code>null</code>. This can be useful for some applications where the value can be undefined or missing.


<lang csharp>bool? value = null</lang>
<syntaxhighlight lang="csharp">bool? value = null</syntaxhighlight>


Unlike C/C++, there is no conversion in C# between other types and <code>Boolean</code>.
Unlike C/C++, there is no conversion in C# between other types and <code>Boolean</code>.

=={{header|C++}}==
=={{header|C++}}==
In C++, there are the constants <code>true</code> and <code>false</code> to represent those values. However, there are numerous implicit conversions to <code>bool</code>, therefore in conditions (and other contexts expecting boolean values), any of the following can be used:
In C++, there are the constants <code>true</code> and <code>false</code> to represent those values. However, there are numerous implicit conversions to <code>bool</code>, therefore in conditions (and other contexts expecting boolean values), any of the following can be used:
Line 670: Line 714:
* any pointer type, where the null pointer gives false and any other pointer gives true
* any pointer type, where the null pointer gives false and any other pointer gives true
* any user-defined type with an implicit conversion operator either to <code>bool</code> or to a built-in type which itself can be converted to <code>bool</code> (i.e. any of the above). The C++ standard library contains one such implicit conversion: the implicit conversion of a stream <code>s</code> to <code>bool</code> gives <code>!s.fail()</code>
* any user-defined type with an implicit conversion operator either to <code>bool</code> or to a built-in type which itself can be converted to <code>bool</code> (i.e. any of the above). The C++ standard library contains one such implicit conversion: the implicit conversion of a stream <code>s</code> to <code>bool</code> gives <code>!s.fail()</code>

=={{header|Clean}}==
=={{header|Clean}}==


The standard library defines a data type <code>Bool</code>, which has exactly two members:
The standard library defines a data type <code>Bool</code>, which has exactly two members:


<lang clean>::Bool = False | True</lang>
<syntaxhighlight lang="clean">::Bool = False | True</syntaxhighlight>


In addition to all the functionality of any other Clean algebraic data type (e.g. [[pattern matching]]), and the specified derived typeclass instances, the built-in guard (“<code>|</code>”) and <code>if</code> syntaxes use Bool.
In addition to all the functionality of any other Clean algebraic data type (e.g. [[pattern matching]]), and the specified derived typeclass instances, the built-in guard (“<code>|</code>”) and <code>if</code> syntaxes use Bool.


As with any other Clean data type, there are no automatic conversions of other types to Bool.
As with any other Clean data type, there are no automatic conversions of other types to Bool.

=={{header|Clojure}}==
=={{header|Clojure}}==
The boolean constants are ''true'' and ''false''. In a conditional context, the only false values are ''false'' and ''nil'' -- every other value is true.
The boolean constants are ''true'' and ''false''. In a conditional context, the only false values are ''false'' and ''nil'' -- every other value is true.

=={{header|CMake}}==
=={{header|CMake}}==
<lang cmake>foreach(var 1 42 ON yes True y Princess
<syntaxhighlight lang="cmake">foreach(var 1 42 ON yes True y Princess
0 OFF no False n Princess-NOTFOUND)
0 OFF no False n Princess-NOTFOUND)
if(var)
if(var)
Line 692: Line 733:
message(STATUS "${var} is false.")
message(STATUS "${var} is false.")
endif()
endif()
endforeach(var)</lang>
endforeach(var)</syntaxhighlight>


<pre>-- 1 is true.
<pre>-- 1 is true.
Line 711: Line 752:


Scripts that want <code>if(TRUE)</code> should require CMake 2.8; do refer to [http://www.cmake.org/cmake/help/cmake-2-8-docs.html#policy:CMP0012 cmake --help-policy CMP0012].
Scripts that want <code>if(TRUE)</code> should require CMake 2.8; do refer to [http://www.cmake.org/cmake/help/cmake-2-8-docs.html#policy:CMP0012 cmake --help-policy CMP0012].

=={{header|COBOL}}==
=={{header|COBOL}}==
===Booleans===
===Booleans===
Booleans are defined as any data item having a <code>PICTURE</code> made up of ones.
Booleans are defined as any data item having a <code>PICTURE</code> made up of ones.
<lang cobol> 01 some-bool PIC 1 BIT.</lang>
<syntaxhighlight lang="cobol"> 01 some-bool PIC 1 BIT.</syntaxhighlight>


The boolean literals <code>B"1"</code> and <code>B"0"</code> represent true and false, respectively.
The boolean literals <code>B"1"</code> and <code>B"0"</code> represent true and false, respectively.
Line 721: Line 761:
===Conditions===
===Conditions===
Prior to COBOL 2002, there was no boolean data type, only ''condition names'' which could be used in conditional expressions. Condition names are subordinate to another data item, have the level-number 88, and are defined with the value(s) which their parent data item must have for them to be set to true. They can be defined like so:
Prior to COBOL 2002, there was no boolean data type, only ''condition names'' which could be used in conditional expressions. Condition names are subordinate to another data item, have the level-number 88, and are defined with the value(s) which their parent data item must have for them to be set to true. They can be defined like so:
<lang cobol> 01 X PIC 9.
<syntaxhighlight lang="cobol"> 01 X PIC 9.
88 X-Is-One VALUE 1.
88 X-Is-One VALUE 1.
88 X-Is-Even VALUE 0 2 4 6 8.
88 X-Is-Even VALUE 0 2 4 6 8.
88 X-Larger-Than-5 VALUE 6 THRU 9.</lang>
88 X-Larger-Than-5 VALUE 6 THRU 9.</syntaxhighlight>


Conditions can be <code>SET</code> to <code>TRUE</code> or <code>FALSE</code>. Setting a condition to <code>TRUE</code> will move the (first) value in the <code>VALUE</code> clause to the parent data item. In COBOL 2002, an optional <code>FALSE</code> clause was added which allowed the condition to be <code>SET</code> to <code>FALSE</code> and consequently set the parent data item to the specified value in the clause. A <code>FALSE</code> clause can only have one value. An example of conditions in action:
Conditions can be <code>SET</code> to <code>TRUE</code> or <code>FALSE</code>. Setting a condition to <code>TRUE</code> will move the (first) value in the <code>VALUE</code> clause to the parent data item. In COBOL 2002, an optional <code>FALSE</code> clause was added which allowed the condition to be <code>SET</code> to <code>FALSE</code> and consequently set the parent data item to the specified value in the clause. A <code>FALSE</code> clause can only have one value. An example of conditions in action:
<lang cobol> PROGRAM-ID. Condition-Example.
<syntaxhighlight lang="cobol"> PROGRAM-ID. Condition-Example.


DATA DIVISION.
DATA DIVISION.
Line 754: Line 794:
DISPLAY "Foo is zero."
DISPLAY "Foo is zero."
END-IF
END-IF
.</lang>
.</syntaxhighlight>


{{out}}
{{out}}
Line 762: Line 802:
Foo is not zero, it is 1.
Foo is not zero, it is 1.
</pre>
</pre>

=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
CoffeeScript is largely based on JavaScript, but that may only serve to confuse you. Your best bet is to learn all the cases:
CoffeeScript is largely based on JavaScript, but that may only serve to confuse you. Your best bet is to learn all the cases:


<lang coffeescript>
<syntaxhighlight lang="coffeescript">
h1 = {foo: "bar"}
h1 = {foo: "bar"}
h2 = {foo: "bar"}
h2 = {foo: "bar"}
Line 795: Line 834:
false and true
false and true
]
]
</syntaxhighlight>
</lang>

=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
The only value in Common Lisp that is false is the symbol <code>nil</code>; all other values are true. The symbol <code>t</code> is the canonical true value.
The only value in Common Lisp that is false is the symbol <code>nil</code>; all other values are true. The symbol <code>t</code> is the canonical true value.
Line 803: Line 841:


For more information, follow the links from [http://www.lispworks.com/documentation/HyperSpec/Body/t_ban.htm CLHS: Type BOOLEAN].
For more information, follow the links from [http://www.lispworks.com/documentation/HyperSpec/Body/t_ban.htm CLHS: Type BOOLEAN].

=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
<lang oberon2>
<syntaxhighlight lang="oberon2">
VAR
VAR
b,c: BOOLEAN;
b,c: BOOLEAN;
Line 812: Line 849:
c := FALSE;
c := FALSE;
...
...
</syntaxhighlight>
</lang>

=={{header|Crystal}}==
=={{header|Crystal}}==
Crystal uses the "truthiness" of a value to determine whether or not to execute the body of an <code>if</code>, <code>unless</code>, <code>while</code>, or <code>until</code> block.
Crystal uses the "truthiness" of a value to determine whether or not to execute the body of an <code>if</code>, <code>unless</code>, <code>while</code>, or <code>until</code> block.
Line 819: Line 855:
As mentioned in the [https://crystal-lang.org/reference/syntax_and_semantics/truthy_and_falsey_values.html language reference], the values <code>nil</code> and <code>false</code>, as well as null pointers are "falsey", all other values are truthy
As mentioned in the [https://crystal-lang.org/reference/syntax_and_semantics/truthy_and_falsey_values.html language reference], the values <code>nil</code> and <code>false</code>, as well as null pointers are "falsey", all other values are truthy


<lang ruby>if false
<syntaxhighlight lang="ruby">if false
puts "false"
puts "false"
elsif nil
elsif nil
Line 827: Line 863:
elsif true && "any other value"
elsif true && "any other value"
puts "finally true!"
puts "finally true!"
end</lang>
end</syntaxhighlight>

=={{header|D}}==
=={{header|D}}==
In D, there are constants <code>false</code> and <code>true</code> to represent their respective values (that also implicitly convert to 0 and 1).
In D, there are constants <code>false</code> and <code>true</code> to represent their respective values (that also implicitly convert to 0 and 1).
Line 838: Line 873:
* Any class reference type, using the "is" operator, the null reference gives false and any other reference gives true;
* Any class reference type, using the "is" operator, the null reference gives false and any other reference gives true;
* Any user-defined type with an implicit conversion operator (opCast) either to bool or to a built-in type which itself can be converted to bool.
* Any user-defined type with an implicit conversion operator (opCast) either to bool or to a built-in type which itself can be converted to bool.

=={{header|Dc}}==
=={{header|Dc}}==
In dc there are no built in boolean values or functions.
In dc there are no built in boolean values or functions.
Adopting the way C codes them appears to be a good idea: <code>0=FALSE</code> and <code>1=TRUE</code>.
Adopting the way C codes them appears to be a good idea: <code>0=FALSE</code> and <code>1=TRUE</code>.

=={{header|Delphi}}==
=={{header|Delphi}}==
In addition to the types defined by [[#Object Pascal|Object Pascal]], Delphi defines the type <code>Bool</code>.
In addition to the types defined by [[#Object Pascal|Object Pascal]], Delphi defines the type <code>Bool</code>.

=={{header|DWScript}}==
=={{header|DWScript}}==
The standard <code>Boolean</code> type has two values: <code>True</code> and <code>False</code>, with <code>Ord(False) = 0</code> and <code>Ord(True) = 1</code>.
The standard <code>Boolean</code> type has two values: <code>True</code> and <code>False</code>, with <code>Ord(False) = 0</code> and <code>Ord(True) = 1</code>.

=={{header|Dyalect}}==
=={{header|Dyalect}}==


Dyalect has a standard <code>Bool</code> type with two values: <code>true</code> and <code>false</code>. Other types in Dyalect support implicit conversion to booleans. All values except <code>false</code>, <code>nil</code>, <code>0</code>, <code>0.0</code> and empty string are converted to <code>true</code>.
Dyalect has a standard <code>Bool</code> type with two values: <code>true</code> and <code>false</code>. Other types in Dyalect support implicit conversion to booleans. All values except <code>false</code> and <code>nil</code> are converted to <code>true</code>.

=={{header|Dylan}}==
=={{header|Dylan}}==
<lang Dylan>#t // <boolean> true
<syntaxhighlight lang="dylan">#t // <boolean> true
#f // <boolean> false</lang>
#f // <boolean> false</syntaxhighlight>
For the purpose of conditional statements, all objects other than <tt>#f</tt> evaluate to true.
For the purpose of conditional statements, all objects other than <tt>#f</tt> evaluate to true.

=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==


Déjà Vu has <code>true</code> and <code>false</code>, two numbers that are equal to 1 and 0 respectively. Every object has a truth value. The only falsy things are numbers equal to zero, empty lists and dictionaries, and zero-length strings and blobs.
Déjà Vu has <code>true</code> and <code>false</code>, two numbers that are equal to 1 and 0 respectively. Every object has a truth value. The only falsy things are numbers equal to zero, empty lists and dictionaries, and zero-length strings and blobs.

=={{header|E}}==
=={{header|E}}==


E defines two basic objects <code>true</code> and <code>false</code>, and the <code>boolean</code> [http://wiki.erights.org/wiki/Guard guard] which accepts them. All builtin operations which take booleans (e.g. the <code>if</code> control structure) coerce the input to boolean.
E defines two basic objects <code>true</code> and <code>false</code>, and the <code>boolean</code> [http://wiki.erights.org/wiki/Guard guard] which accepts them. All builtin operations which take booleans (e.g. the <code>if</code> control structure) coerce the input to boolean.


<lang e>? if (true) { "a" } else { "b" }
<syntaxhighlight lang="e">? if (true) { "a" } else { "b" }
# value: "a"
# value: "a"


Line 873: Line 901:


? if (90) { "a" } else { "b" }
? if (90) { "a" } else { "b" }
# problem: the int 90 doesn't coerce to a boolean</lang>
# problem: the int 90 doesn't coerce to a boolean</syntaxhighlight>


No objects in the standard library coerce to boolean, but user-written objects may choose to do so; they can then be used in place of booleans.
No objects in the standard library coerce to boolean, but user-written objects may choose to do so; they can then be used in place of booleans.


<lang e>? def bowlian {
<syntaxhighlight lang="e">? def bowlian {
> to __conformTo(guard) {
> to __conformTo(guard) {
> if (guard == boolean) { return true }
> if (guard == boolean) { return true }
Line 883: Line 911:
> }
> }
> if (bowlian) { "a" } else { "b" }
> if (bowlian) { "a" } else { "b" }
# value: "a"</lang>
# value: "a"</syntaxhighlight>

=={{header|EasyLang}}==
EasyLang does not have built-in boolean types or constants. Operators that "return" a boolean type (e.g. >, <=) cannot be used outside of conditional statements and loops.

You can use 1 or 0 in place of true and false.

<syntaxhighlight lang="easylang">
boolNumber = 1
if boolNumber = 1
print "True"
else
print "False"
.
</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
"All that which is not false is true" - Attribué à L. Wittgenstein - The only false value is the boolean #f. '''All''' other objects, including the empty list or null or 0 ..- evaluate to #t = true.
"All that which is not false is true" - Attribué à L. Wittgenstein - The only false value is the boolean #f. '''All''' other objects, including the empty list or null or 0 ..- evaluate to #t = true.
<lang scheme>
<syntaxhighlight lang="scheme">
(not #t) → #f
(not #t) → #f
(not #f) → #t
(not #f) → #t
(not null) → #f
(not null) → #f
(not 0) → #f
(not 0) → #f
</syntaxhighlight>
</lang>

=={{header|Ecstasy}}==
Ecstasy's defines [https://github.com/xtclang/xvm/blob/master/lib_ecstasy/src/main/x/ecstasy/Boolean.x an enumeration named Boolean], which contains the values <span style="background-color: #e5e4e2"><tt>&nbsp;False&nbsp;</tt></span> and <span style="background-color: #e5e4e2"><tt>&nbsp;True&nbsp;</tt></span>.
<syntaxhighlight lang="java">
module GeorgeBoole {
@Inject Console console;

void run() {
Boolean f = False;
assert !f == True;

// methods like "and", "or", "xor", and "not" are the same as
// the operators "&"/"&&", "|"/"||", "^"/"^^", and the unary "~"
assert True.and(False) == True & False == False;
assert True.or(False) == True | False == True;
assert True.xor(False) == True ^ False == True;
assert True.not() == ~True == False;

console.print($"0==1 = {0==1}");
console.print($"!False = {!False}");
}
}
</syntaxhighlight>

{{out}}
<pre>
0==1 = False
!False = True
</pre>


=={{header|EGL}}==
=={{header|EGL}}==
Line 898: Line 969:
A boolean can be converted to a string ("true" or "false") using StrLib.booleanAsString(boolean);
A boolean can be converted to a string ("true" or "false") using StrLib.booleanAsString(boolean);


<syntaxhighlight lang="egl">
<lang EGL>
myBool boolean = 0;
myBool boolean = 0;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
Line 919: Line 990:
myInt = true;
myInt = true;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 934: Line 1,005:
myInt: true
myInt: true
</pre>
</pre>

=={{header|Elena}}==
=={{header|Elena}}==
ELENA uses the system'BaseBoolValue class, which has two singleton sub-classes: system'true and system'false. E.g. an expression like 5 == 5 returns system'true.
ELENA uses the system'BaseBoolValue class, which has two singleton sub-classes: system'true and system'false. E.g. an expression like 5 == 5 returns system'true.
There is a Boolean variable : system'Boolean.
There is a Boolean variable : system'Boolean.

=={{header|Elixir}}==
=={{header|Elixir}}==
Elixir utilizes Erlang's definition of boolean types; they're defined as the atoms <tt>:true</tt> and <tt>:false</tt>. No other type is equal to true or false.
Elixir utilizes Erlang's definition of boolean types; they're defined as the atoms <tt>:true</tt> and <tt>:false</tt>. No other type is equal to true or false.
<syntaxhighlight lang="elixir">
<lang Elixir>
iex(1)> true === :true
iex(1)> true === :true
true
true
Line 948: Line 1,017:
iex(3)> true === 1
iex(3)> true === 1
false
false
</syntaxhighlight>
</lang>


nil (also defined as an atom, <tt>:nil</tt>) is not equal to false.
nil (also defined as an atom, <tt>:nil</tt>) is not equal to false.
<syntaxhighlight lang="elixir">
<lang Elixir>
iex(4)> nil === :nil
iex(4)> nil === :nil
true
true
iex(5)> nil === false
iex(5)> nil === false
false
false
</syntaxhighlight>
</lang>

=={{header|Elm}}==
=={{header|Elm}}==
<syntaxhighlight lang="elm">
<lang Elm>
--True and False directly represent Boolean values in Elm
--True and False directly represent Boolean values in Elm
--For eg to show yes for true and no for false
--For eg to show yes for true and no for false
Line 1,003: Line 1,071:
display expr=
display expr=
div [] [ text ( toString expr ++ "-->" ++ toString(evaluate expr) ) ]
div [] [ text ( toString expr ++ "-->" ++ toString(evaluate expr) ) ]
--END</lang>
--END</syntaxhighlight>

=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
Symbol <code>nil</code> is false and symbol <code>t</code> is true. Both are self-evaluating, being variables whose value is their own symbol. See [http://www.gnu.org/software/emacs/manual/html_node/elisp/nil-and-t.html the elisp manual] for more.
Symbol <code>nil</code> is false and symbol <code>t</code> is true. Both are self-evaluating, being variables whose value is their own symbol. See [http://www.gnu.org/software/emacs/manual/html_node/elisp/nil-and-t.html the elisp manual] for more.


In an <code>if</code> and similar, <code>nil</code> is false and anything else is true. To make that clear docstrings etc say "non-nil" for true. (See last item in [http://www.gnu.org/software/emacs/manual/html_node/elisp/Documentation-Tips.html elisp manual documentation tips].)
In an <code>if</code> and similar, <code>nil</code> is false and anything else is true. To make that clear docstrings etc say "non-nil" for true. (See last item in [http://www.gnu.org/software/emacs/manual/html_node/elisp/Documentation-Tips.html elisp manual documentation tips].)

=={{header|EMal}}==
<syntaxhighlight lang="emal">
^|EMal has a dedicated Logical type expressed by the logic keyword.
|It's not nullable and holds the two values false and true.
|There are no implicit conversions, but explicit conversions
|from/to int (0,1) or text ("⊥", "⊤") are allowed.
|^
logic booleanTrue = true
logic booleanFalse = false
if 2 > 1 and true and not false
writeLine("true: " + true + ", false: " + false)
end
if false == logic!0
writeLine("explicit conversion from integer")
end
if true == logic!"⊤"
writeLine("explicit conversion from text")
end
writeLine(int!true) # is one
writeLine(text!false) # is "⊥"
</syntaxhighlight>
{{out}}
<pre>
true: ⊤, false: ⊥
explicit conversion from integer
explicit conversion from text
1
</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
Erlang doesn't technically define boolean types. Instead, the atoms <tt>true</tt> and <tt>false</tt> are used. However, they are integrated well enough into the language there should be no problem with that as long as you don't expect false and true to mean anything but literal false and true.
Erlang doesn't technically define boolean types. Instead, the atoms <tt>true</tt> and <tt>false</tt> are used. However, they are integrated well enough into the language there should be no problem with that as long as you don't expect false and true to mean anything but literal false and true.


<lang erlang>1> 1 < 2.
<syntaxhighlight lang="erlang">1> 1 < 2.
true
true
2> 1 < 1.
2> 1 < 1.
false
false
3> 0 == false.
3> 0 == false.
false</lang>
false</syntaxhighlight>

=={{header|Excel}}==
=={{header|Excel}}==
The Logical category of functions includes the constants TRUE() and FALSE() which are displayed without the parantheses in cells. There are logical functions such as AND and OR too. For an AND truth table of two variables, take 3 cells, say A1,B1 and C1. In C1 type in :
The Logical category of functions includes the constants TRUE() and FALSE() which are displayed without the parantheses in cells. There are logical functions such as AND and OR too. For an AND truth table of two variables, take 3 cells, say A1,B1 and C1. In C1 type in :


<lang excel>=AND(A1;B1)</lang>
<syntaxhighlight lang="excel">=AND(A1;B1)</syntaxhighlight>


Copy this until C4. Now as values are filled in from A1-A4 and B1-B4, C1-C4 gets updated.
Copy this until C4. Now as values are filled in from A1-A4 and B1-B4, C1-C4 gets updated.


<lang>0 0 FALSE
<syntaxhighlight lang="text">0 0 FALSE
0 1 FALSE
0 1 FALSE
1 0 FALSE
1 0 FALSE
1 1 TRUE</lang>
1 1 TRUE</syntaxhighlight>

=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
The type bool is an abbreviation for the .NET framework type <code>System.Boolean</code>.
The type bool is an abbreviation for the .NET framework type <code>System.Boolean</code>.
<lang fsharp>type bool = System.Boolean</lang>
<syntaxhighlight lang="fsharp">type bool = System.Boolean</syntaxhighlight>
Instances of this type have values of either <code>true</code> or <code>false</code>.
Instances of this type have values of either <code>true</code> or <code>false</code>.

=={{header|Factor}}==
=={{header|Factor}}==
In Factor any value except <code>f</code> is true, with <code>t</code> being the canonical true value.
In Factor any value except <code>f</code> is true, with <code>t</code> being the canonical true value.

=={{header|FALSE}}==
=={{header|FALSE}}==
Zero is false and non-zero is true. This is used by the if and while operators ('''?''' and '''#'''). Comparators ('''=''' and '''<''') yield -1 for true and 0 for false.
Zero is false and non-zero is true. This is used by the if and while operators ('''?''' and '''#'''). Comparators ('''=''' and '''<''') yield -1 for true and 0 for false.

=={{header|Fantom}}==
=={{header|Fantom}}==


Conditional statements must return a <code>sys::Bool</code>, and the only two values are <code>true</code> and <code>false</code>.
Conditional statements must return a <code>sys::Bool</code>, and the only two values are <code>true</code> and <code>false</code>.

=={{header|Forth}}==
=={{header|Forth}}==
In conditionals, zero is false, non-zero is true. There are predefined constants for the canonical forms. For FORTH-83 or later, FALSE is zero and TRUE is -1 (all bits set). For earlier FORTH standards, FALSE is zero and TRUE is 1.
In conditionals, zero is false, non-zero is true. There are predefined constants for the canonical forms. For FORTH-83 or later, FALSE is zero and TRUE is -1 (all bits set). For earlier FORTH standards, FALSE is zero and TRUE is 1.
<lang forth>TRUE . \ -1
<syntaxhighlight lang="forth">TRUE . \ -1
FALSE . \ 0</lang>
FALSE . \ 0</syntaxhighlight>

=={{header|Fortran}}==
=={{header|Fortran}}==
Fortran started off in 1957 with only floating-point and fixed-point variables, so any calculations in the style of Boolean arithmetic would be done with integer values such as zero and not-zero, using multiplication and addition for '''and''' and '''or'''.
Fortran started off in 1957 with only floating-point and fixed-point variables, so any calculations in the style of Boolean arithmetic would be done with integer values such as zero and not-zero, using multiplication and addition for '''and''' and '''or'''.
Line 1,057: Line 1,147:
Fortran 66 introduced a '''logical''' data type which can be set to either '''.true.''' or '''.false.''' or be generated via logical expressions such as <=, etc. Such variables cannot be used in normal arithmetic with operators such as +-*/ but only with logical operators such as .OR. and so on. If via the EQUIVALENCE statement their numerical values (or, bit patterns) are inspected as say an integer, the values may well not be as anticipated and differ between computers and compilers. For instance, on the Burroughs 6700 an '''integer''' variable equivalenced to a '''logical''' variable would appear as '''.true.''' if odd, '''.false.''' if even.
Fortran 66 introduced a '''logical''' data type which can be set to either '''.true.''' or '''.false.''' or be generated via logical expressions such as <=, etc. Such variables cannot be used in normal arithmetic with operators such as +-*/ but only with logical operators such as .OR. and so on. If via the EQUIVALENCE statement their numerical values (or, bit patterns) are inspected as say an integer, the values may well not be as anticipated and differ between computers and compilers. For instance, on the Burroughs 6700 an '''integer''' variable equivalenced to a '''logical''' variable would appear as '''.true.''' if odd, '''.false.''' if even.


The default storage size of a LOGICAL variable is the same as the default storage size of an INTEGER variable, which for many systems is 32 bits. This is done to simplify calculations of record sizes, or the alignment of variables in COMMON storage areas. It is usually possible to declare variables with certain byte sizes (normally only powers of two) so that LOGICAL*1 or similar declarations may be available. If used however there may arise alignment issues with adjacent variables of other types (such as REAL) that may require padding to even word boundaries for best access. Consider <lang Fortran> TYPE MIXED
The default storage size of a LOGICAL variable is the same as the default storage size of an INTEGER variable, which for many systems is 32 bits. This is done to simplify calculations of record sizes, or the alignment of variables in COMMON storage areas. It is usually possible to declare variables with certain byte sizes (normally only powers of two) so that LOGICAL*1 or similar declarations may be available. If used however there may arise alignment issues with adjacent variables of other types (such as REAL) that may require padding to even word boundaries for best access. Consider <syntaxhighlight lang="fortran"> TYPE MIXED
LOGICAL*1 LIVE
LOGICAL*1 LIVE
REAL*8 VALUE
REAL*8 VALUE
END TYPE MIXED
END TYPE MIXED
TYPE(MIXED) STUFF(100)</lang>
TYPE(MIXED) STUFF(100)</syntaxhighlight>
The array STUFF might occupy 900 bytes, or, 1600 bytes if each double-precision value has to be aligned to an eight-byte boundary. In the latter case, it may be better to declare LIVE and VALUE to be separate hundred-element arrays as in <lang Fortran> TYPE MIXED
The array STUFF might occupy 900 bytes, or, 1600 bytes if each double-precision value has to be aligned to an eight-byte boundary. In the latter case, it may be better to declare LIVE and VALUE to be separate hundred-element arrays as in <syntaxhighlight lang="fortran"> TYPE MIXED
LOGICAL*1 LIVE(100)
LOGICAL*1 LIVE(100)
REAL*8 VALUE(100)
REAL*8 VALUE(100)
END TYPE MIXED
END TYPE MIXED
TYPE(MIXED) STUFF</lang>
TYPE(MIXED) STUFF</syntaxhighlight>
Except that now only hundred-element variables of type MIXED can be declared. Either way, the record size needed for a disc file holding such items will need careful thought.
Except that now only hundred-element variables of type MIXED can be declared. Either way, the record size needed for a disc file holding such items will need careful thought.

=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
In addition to the types defined by [[#Object Pascal|Object Pascal]], free Pascal defines the <code>qWordBool</code>, that has a <code>sizeOf</code> eight.<br>
In addition to the types defined by [[#Object Pascal|Object Pascal]], free Pascal defines the <code>qWordBool</code>, that has a <code>sizeOf</code> eight.<br>
Furthermore, True and False are not keywords from FPC v3.0.0. It is possible to assign any value to true and false, like strings but even objects.<br>
Furthermore, True and False are not keywords from FPC v3.0.0. It is possible to assign any value to true and false, like strings but even objects.<br>
<lang pascal>{$mode objfpc}{$ifdef mswindows}{$apptype console}{$endif}
<syntaxhighlight lang="pascal">{$mode objfpc}{$ifdef mswindows}{$apptype console}{$endif}
const
const
true = 'true';
true = 'true';
Line 1,079: Line 1,168:
writeln(true);
writeln(true);
writeln(false);
writeln(false);
end.</lang>
end.


[ EDIT ]

See https://wiki.freepascal.org/Boolean

While you can assign values to true and false, it has now nothing to do with the boolean values....
Try with this function:

FUNCTION IsNatural ( CONST num: VARIANT ): BOOLEAN;

BEGIN

IsNatural := ( num > 0 );

END;

</syntaxhighlight>
JPD 2022/08/02
=={{header|Frink}}==
=={{header|Frink}}==
The literal boolean values are called <CODE>true</CODE> and <CODE>false</CODE>. In addition, in conditional expressions, the following are treated as true:
The literal boolean values are called <CODE>true</CODE> and <CODE>false</CODE>. In addition, in conditional expressions, the following are treated as true:
Line 1,091: Line 1,197:
* The empty string
* The empty string
* The special value <CODE>undef</CODE>
* The special value <CODE>undef</CODE>

=={{header|Futhark}}==
=={{header|Futhark}}==


Futhark has a <code>bool</code> type, with the two values <code>True</code> and <code>False</code>. They are used for branching.
Futhark has a <code>bool</code> type, with the two values <code>True</code> and <code>False</code>. They are used for branching.


=={{header|FutureBasic}}==
FB recognizes two types for boolean truth values: BOOL and boolean. There is a subtle difference between the two. A BOOL will accept without complaint the macros YES, and NO, the equivalent native FB constants, _true, and _false, and, of course, 0 and 1. However, although a BOOL can be assigned other values, it will throw a clang (FB"s native compiler) warning as with this example:
<syntaxhighlight lang="futurebasic">
window 1
BOOL boolTest
boolTest = -1
print boolTest
HandleEvents
</syntaxhighlight>
When compiled this code generates this warning:
<syntaxhighlight lang="futurebasic">
implicit conversion from constant value -1 to 'BOOL'; the only well defined values for 'BOOL' are YES and NO [-Wobjc-bool-constant-conversion]
</syntaxhighlight>
On the other hand, a Boolean can be assigned not only YES, NO, _true, or _false, and 0 or 1, but also other values, such as the common -1, and compile without complaint.

Since FB can also work with objects, native BOOLs and booleans need to be converted to objects as demonstrated in the code below.

Trivia: Because NULL and _nil zero values in FB, they evaluate to "NO" or “_false” in conditional expressions.
<syntaxhighlight lang="futurebasic">
void local fn BooleanExercise
BOOL areEqual = (1 == 1) // areEqual is YES
BOOL areNotEqual = not areEqual /* areNotEqual is converted to: areEqual = (-(1 == 1)). -1 throws a clang warning.
NOTE: FB does not accept the "!" shorthand for "not", i.e. !areEqual, common in other languages. */
print "areEqual == "; areEqual
print "areNotEqual == "; areNotEqual
print
// Boolean types assigned values outside YES or NO compile without complaint.
boolean minusOneTest = -1
print "minusOneTest == "; minusOneTest
// Typical boolean value is use
BOOL flatterRosettaReader = YES
if (flatterRosettaReader)
print
print @"Rosetta Code programmers understand booleans."
print
end if
// Defined Core Foundation boolean values
print "kCFBooleanTrue == "; kCFBooleanTrue
print "kCFBooleanFalse == "; kCFBooleanFalse
print
// Number object assigned literal value
CFNumberRef booleanObject = @(YES)
print "booleanObject == "; booleanObject
print
// Number object created programmatically
booleanObject = NO
print "booleanObject variable reassigned as N0 == "; fn NumberWithBool( booleanObject )
print
end fn

window 1

fn BooleanExercise

HandleEvents
</syntaxhighlight>
{{output}}
<pre>
areEqual == 1
areNotEqual == 0

minusOneTest == -1

Rosetta Code programmers understand booleans.

kCFBooleanTrue == 1
kCFBooleanFalse == 0

booleanObject == 1

booleanObject variable reassigned as N0 == 0
</pre>


=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=65324112fde86d51937b9cfcca0c51f9 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=65324112fde86d51937b9cfcca0c51f9 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim bX As Boolean
Dim bX As Boolean


Line 1,105: Line 1,290:
Print bX
Print bX


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,111: Line 1,296:
True
True
</pre>
</pre>

=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>1 < 2;
<syntaxhighlight lang="gap">1 < 2;
# true
# true


Line 1,125: Line 1,309:


fail = fail;
fail = fail;
# true</lang>
# true</syntaxhighlight>

=={{header|Go}}==
=={{header|Go}}==
Go defines a built-in data type <code>bool</code>, which has exactly two values, represented by the keywords <code>true</code> and <code>false</code>. There is no conversion between booleans and other data types. Conditionals require a boolean value, so if i is a numeric type, for example, you must spell out <tt>if i != 0 {</tt> if you wish to interpret it as boolean.
Go defines a built-in data type <code>bool</code>, which has exactly two values, represented by the keywords <code>true</code> and <code>false</code>. There is no conversion between booleans and other data types. Conditionals require a boolean value, so if i is a numeric type, for example, you must spell out <tt>if i != 0 {</tt> if you wish to interpret it as boolean.
Line 1,132: Line 1,315:
The template package however, uses a different rule for <tt>if</tt> actions. There, it is testing if a "pipeline" is "empty" where the empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.
The template package however, uses a different rule for <tt>if</tt> actions. There, it is testing if a "pipeline" is "empty" where the empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.


<lang go>
<syntaxhighlight lang="go">
package main
package main


Line 1,158: Line 1,341:
bolStr, _ := strconv.ParseBool(str1)
bolStr, _ := strconv.ParseBool(str1)
fmt.Println("After :", reflect.TypeOf(bolStr)) // prt After : bool
fmt.Println("After :", reflect.TypeOf(bolStr)) // prt After : bool
}</lang>
}</syntaxhighlight>

=={{header|Groovy}}==
=={{header|Groovy}}==
[[Groovy]] has a boolean "primitive" type and a Boolean "object wrapper" type directly derived from [[Java]]. See the Java solution to this task for more details.
[[Groovy]] has a boolean "primitive" type and a Boolean "object wrapper" type directly derived from [[Java]]. See the Java solution to this task for more details.


Unlike Java, any null reference converts to a boolean "false", while any non-null object reference converts to a boolean "true"... EXCEPT if that object has a specific defined conversion to boolean "false". For example, for any numeric type, any zero value representation converts to "false" and any non-zero value converts to "true". For any collection type, non-empty converts to "true" and empty converts to "false".
Unlike Java, any null reference converts to a boolean "false", while any non-null object reference converts to a boolean "true"... EXCEPT if that object has a specific defined conversion to boolean "false". For example, for any numeric type, any zero value representation converts to "false" and any non-zero value converts to "true". For any collection type, non-empty converts to "true" and empty converts to "false".

=={{header|Haskell}}==
=={{header|Haskell}}==


The Haskell standard [http://haskell.org/haskellwiki/Prelude Prelude] defines a data type <code>Bool</code>, which has exactly two members:
The Haskell standard [http://haskell.org/haskellwiki/Prelude Prelude] defines a data type <code>Bool</code>, which has exactly two members:


<lang haskell>data Bool = False | True deriving (Eq, Ord, Enum, Read, Show, Bounded)</lang>
<syntaxhighlight lang="haskell">data Bool = False | True deriving (Eq, Ord, Enum, Read, Show, Bounded)</syntaxhighlight>


In addition to all the functionality of any other Haskell algebraic data type (e.g. [[pattern matching]]), and the specified derived typeclass instances (e.g. <code>False == False</code>, <code>succ False == True</code>, <code>(maxBound :: Bool) == True</code>, etc.), the built-in guard (“<code>|</code>”) and <code>if</code> syntaxes use Bool.
In addition to all the functionality of any other Haskell algebraic data type (e.g. [[pattern matching]]), and the specified derived typeclass instances (e.g. <code>False == False</code>, <code>succ False == True</code>, <code>(maxBound :: Bool) == True</code>, etc.), the built-in guard (“<code>|</code>”) and <code>if</code> syntaxes use Bool.


As with any other Haskell data type, there are no automatic conversions of other types to Bool.
As with any other Haskell data type, there are no automatic conversions of other types to Bool.

=={{header|HicEst}}==
=={{header|HicEst}}==
Zero is false, non-zero is true. Numbers also work in place of boolean expressions following this rule.
Zero is false, non-zero is true. Numbers also work in place of boolean expressions following this rule.

=={{header|HolyC}}==
=={{header|HolyC}}==
In HolyC, there are the reserved keywords `TRUE` and `FALSE`. Variables to hold these values are declared as `Bool`.
In HolyC, there are the reserved keywords `TRUE` and `FALSE`. Variables to hold these values are declared as `Bool`.
Line 1,186: Line 1,365:
* Any floating point type, where again, 0 gives false and everything else gives true.
* Any floating point type, where again, 0 gives false and everything else gives true.
* Any pointer type, where the null pointer gives false and any other pointer gives true.
* Any pointer type, where the null pointer gives false and any other pointer gives true.

=={{header|i}}==
=={{header|i}}==
Any non-zero number is true in 'i'.
Any non-zero number is true in 'i'.
<lang i>main
<syntaxhighlight lang="i">main
//Bits aka Booleans.
//Bits aka Booleans.
b $= bit()
b $= bit()
Line 1,209: Line 1,387:
b $= 0
b $= 0
print(b)
print(b)
}</lang>
}</syntaxhighlight>

=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon do not use Boolean values for flow control. Rather they use success (returning a result, any result even a null) or failure (a signal) for this purpose. Built-in controls support not, and (&), and or (|). For an example of how this works, see [[Short-circuit_evaluation#Icon_and_Unicon|Short Circuit Evaluation]]. Icon and Unicon do support bit operations on integers which could be used to record Boolean state. See also [[Logical_operations#Icon_and_Unicon|Logical Operations]] for an example of how and when Boolean values might be implemented.
Icon and Unicon do not use Boolean values for flow control. Rather they use success (returning a result, any result even a null) or failure (a signal) for this purpose. Built-in controls support not, and (&), and or (|). For an example of how this works, see [[Short-circuit_evaluation#Icon_and_Unicon|Short Circuit Evaluation]]. Icon and Unicon do support bit operations on integers which could be used to record Boolean state. See also [[Logical_operations#Icon_and_Unicon|Logical Operations]] for an example of how and when Boolean values might be implemented.

=={{header|Idris}}==
=={{header|Idris}}==
<lang idris>Idris> :doc Bool
<syntaxhighlight lang="idris">Idris> :doc Bool
Data type Prelude.Bool.Bool : Type
Data type Prelude.Bool.Bool : Type
Boolean Data Type
Boolean Data Type
Line 1,224: Line 1,400:


True : Bool
True : Bool
</syntaxhighlight>
</lang>

=={{header|Inform 6}}==
=={{header|Inform 6}}==
Inform 6 has the constants <code>true</code> and <code>false</code>, which are identical to <code>1</code> and <code>0</code> respectively. One of these values will always be yielded by a condition operator (an operator that yields a boolean value). In addition, any non-zero value is considered to be true.
Inform 6 has the constants <code>true</code> and <code>false</code>, which are identical to <code>1</code> and <code>0</code> respectively. One of these values will always be yielded by a condition operator (an operator that yields a boolean value). In addition, any non-zero value is considered to be true.

=={{header|Inform 7}}==
=={{header|Inform 7}}==
The Boolean type is called "truth state" and has the values "true" and "false".
The Boolean type is called "truth state" and has the values "true" and "false".


However, Inform 7 distinguishes between Boolean values and conditions. Comparison expressions do not return truth states, and truth state expressions cannot be used directly in conditional statements. There is a conversion from condition to truth state:
However, Inform 7 distinguishes between Boolean values and conditions. Comparison expressions do not return truth states, and truth state expressions cannot be used directly in conditional statements. There is a conversion from condition to truth state:
<lang inform7>let B be whether or not 123 is greater than 100;</lang>
<syntaxhighlight lang="inform7">let B be whether or not 123 is greater than 100;</syntaxhighlight>
And truth states can be used in conditions by adding an explicit comparison:
And truth states can be used in conditions by adding an explicit comparison:
<lang inform7>if B is true, say "123 is greater than 100."</lang>
<syntaxhighlight lang="inform7">if B is true, say "123 is greater than 100."</syntaxhighlight>


Phrases (functions) cannot be defined to return a truth state directly. Instead, they are defined using "to decide whether" (or "to decide if") and can then be used as conditions:
Phrases (functions) cannot be defined to return a truth state directly. Instead, they are defined using "to decide whether" (or "to decide if") and can then be used as conditions:
<lang inform7>To decide whether the CPU is working correctly:
<syntaxhighlight lang="inform7">To decide whether the CPU is working correctly:
if 123 is greater than 100, decide yes;
if 123 is greater than 100, decide yes;
otherwise decide no.
otherwise decide no.
Line 1,246: Line 1,420:
let B be whether or not the CPU is working correctly;
let B be whether or not the CPU is working correctly;
[...or use as a condition]
[...or use as a condition]
if the CPU is working correctly, say "Whew."</lang>
if the CPU is working correctly, say "Whew."</syntaxhighlight>

=={{Header|Insitux}}==

Simply <code>true</code> and <code>false</code>, however, anything which is not <code>false</code> or <code>null</code> is considered truthy.


=={{header|J}}==
=={{header|J}}==


False is <tt>0</tt>, true is <tt>1</tt>. This is an [http://keiapl.info/anec/#Maple advantage].
False is <tt>0</tt>, true is <tt>1</tt>. This is an [http://web.archive.org/web/20080703182354/http://keiapl.info/anec/ advantage (search for Maple)].


This approach also works well with [[wp:Bayes'_theorem|Bayes' theorem]], as false matches 0% probability and true matches 100% probability.
This approach also works well with [[wp:Bayes'_theorem|Bayes' theorem]], as false matches 0% probability and true matches 100% probability.

=={{header|Java}}==
=={{header|Java}}==
<p>
Java has <tt>true</tt> and <tt>false</tt> keywords, representing the only values of type <tt>boolean</tt>. There are also object wrappers <tt>Boolean.TRUE</tt> and <tt>Boolean.FALSE</tt>, of type <tt>Boolean</tt> which may be un-boxed into <tt>boolean</tt>s (auto-unboxed in Java 1.5+). There are no automatic conversions from any other types into <tt>boolean</tt>, and it is a compile-time error to use any type other than <tt>boolean</tt> or <tt>Boolean</tt> in a place that expects a <tt>boolean</tt> (e.g. if-statement condition, while-statement condition, operand of a logical operator, etc.).
In Java, <code>true</code> and <code>false</code> are used to reference a <code>boolean</code> value.<br />
There is no use of <kbd>0</kbd> and <kbd>1</kbd>, or <kbd>undefined</kbd> vs. <kbd>defined</kbd>.
</p>
<p>
As with the other primitive data-types, <code>boolean</code> has a wrapper class, <code>Boolean</code>, which includes a
set of valuable <kbd>boolean</kbd> operations.
</p>
<syntaxhighlight lang="java">
boolean valueA = true;
boolean valueB = false;
</syntaxhighlight>
<p>
Or.
</p>
<syntaxhighlight lang="java">
Boolean valueA = Boolean.TRUE;
Boolean valueB = Boolean.FALSE;
</syntaxhighlight>
<p>
Additionally.
</p>
<syntaxhighlight lang="java">
Boolean valueA = Boolean.valueOf(true);
Boolean valueB = Boolean.valueOf(false);
</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 1,268: Line 1,470:


(source: [http://www.ecma-international.org/publications/standards/Ecma-262.htm ECMAScript Language Reference])
(source: [http://www.ecma-international.org/publications/standards/Ecma-262.htm ECMAScript Language Reference])

=={{header|Joy}}==
The truth literals are <code>true</code> and <code>false</code>. In a conditional context, <code>false</code>, numerical values (including characters) of zero, empty lists and empty sets are evaluated as false.


=={{header|jq}}==
=={{header|jq}}==
Line 1,288: Line 1,493:


Other objects do not represent boolean values and cannot be used in conditional expressions, for example:
Other objects do not represent boolean values and cannot be used in conditional expressions, for example:
<lang julia>julia> if 1
<syntaxhighlight lang="julia">julia> if 1
println("true")
println("true")
end
end
ERROR: type: non-boolean (Int64) used in boolean context</lang>
ERROR: type: non-boolean (Int64) used in boolean context</syntaxhighlight>
However, integers can be converted to boolean types with the <code>bool()</code> function (which treats nonzero values as <code>true</code>)
However, integers can be converted to boolean types with the <code>bool()</code> function (which treats nonzero values as <code>true</code>)
<lang julia>julia> bool(-2:2)
<syntaxhighlight lang="julia">julia> bool(-2:2)
5-element Bool Array:
5-element Bool Array:
true
true
Line 1,299: Line 1,504:
false
false
true
true
true</lang>
true</syntaxhighlight>

=={{header|KonsolScript}}==
=={{header|KonsolScript}}==
The Boolean type has two values: <code>true</code> and <code>false</code>
The Boolean type has two values: <code>true</code> and <code>false</code>
Line 1,308: Line 1,512:
* String: the empty (zero-length) string is <code>false</code>; otherwise <code>true</code>
* String: the empty (zero-length) string is <code>false</code>; otherwise <code>true</code>
`
`

=={{header|Kotlin}}==
=={{header|Kotlin}}==
Booleans in Kotlin are given by the literals true and false, case sensitive, which are the only instances of the class Boolean.
Booleans in Kotlin are given by the literals true and false, case sensitive, which are the only instances of the class Boolean.

=={{header|LabVIEW}}==
=={{header|LabVIEW}}==
{{VI solution|LabVIEW_Boolean_values.png}}
{{VI solution|LabVIEW_Boolean_values.png}}

=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
Predefined constants are true and false:
Predefined constants are true and false:
<lang scheme>
<syntaxhighlight lang="scheme">
{if true then YES else NO}
{if true then YES else NO}
-> YES
-> YES
{if false then YES else NO}
{if false then YES else NO}
-> NO
-> NO
</syntaxhighlight>
</lang>
Following the lambda calculus user defined booleans can be built
Following the lambda calculus user defined booleans can be built
<lang scheme>
<syntaxhighlight lang="scheme">
{def TRUE {lambda {:a :b} :a}}
{def TRUE {lambda {:a :b} :a}}
-> TRUE
-> TRUE
Line 1,337: Line 1,538:
-> no
-> no


</syntaxhighlight>
</lang>

=={{header|Lasso}}==
=={{header|Lasso}}==
Comparisons are evaluated in Lasso as either true of false, so "1 == 2" will evaluate as true, and "1 == 1" will evaluate as true.
Comparisons are evaluated in Lasso as either true of false, so "1 == 2" will evaluate as true, and "1 == 1" will evaluate as true.
Line 1,344: Line 1,544:
A variable can also be assigned a boolean type, and as such then holds either true of false states.
A variable can also be assigned a boolean type, and as such then holds either true of false states.


<lang Lasso >!true
<syntaxhighlight lang="lasso ">!true
// => false
// => false


Line 1,354: Line 1,554:


$x = false
$x = false
$x // => false</lang>
$x // => false</syntaxhighlight>


In a conditional, if the result is the integer 0, it is also evaluated as boolean false.
In a conditional, if the result is the integer 0, it is also evaluated as boolean false.
If the conditional results in an integer greater than zero, it is evaluated as boolean true.
If the conditional results in an integer greater than zero, it is evaluated as boolean true.


<lang Lasso >local(x = string)
<syntaxhighlight lang="lasso ">local(x = string)
// size is 0
// size is 0
#x->size ? 'yes' | 'no'
#x->size ? 'yes' | 'no'
Line 1,365: Line 1,565:
local(x = '123fsfsd')
local(x = '123fsfsd')
// size is 8
// size is 8
#x->size ? 'yes' | 'no'</lang>
#x->size ? 'yes' | 'no'</syntaxhighlight>


{{out}}
{{out}}
<pre>no
<pre>no
yes</pre>
yes</pre>

=={{header|Latitude}}==
=={{header|Latitude}}==


Line 1,376: Line 1,575:


By convention, objects which are used to represent failure are considered falsy. For instance, the standard library <code>'unit-test</code> module provides the <code>FailedTest</code> object, which is returned when a unit test fails. This object (and its children) test falsy when used as a conditional.
By convention, objects which are used to represent failure are considered falsy. For instance, the standard library <code>'unit-test</code> module provides the <code>FailedTest</code> object, which is returned when a unit test fails. This object (and its children) test falsy when used as a conditional.

=={{header|LFE}}==
=={{header|LFE}}==
<lang lisp>
<syntaxhighlight lang="lisp">
> 'true
> 'true
true
true
Line 1,387: Line 1,585:
> (or 'false 'true)
> (or 'false 'true)
true
true
</syntaxhighlight>
</lang>


=={{header|Lingo}}==
=={{header|Lingo}}==
Lingo has the constants TRUE and FALSE. In numerical context they have the values 1 and 0. In boolean context any nonzero integer evaluates to TRUE.
Lingo has the constants TRUE and FALSE. In numerical context they have the values 1 and 0. In boolean context any nonzero integer evaluates to TRUE.
<lang lingo>put TRUE
<syntaxhighlight lang="lingo">put TRUE
-- 1
-- 1
put FALSE
put FALSE
-- 0
-- 0
if 23 then put "Hello"
if 23 then put "Hello"
-- "Hello"</lang>
-- "Hello"</syntaxhighlight>

=={{header|Little}}==
=={{header|Little}}==
For conditionals, numeric variables (including poly variables
For conditionals, numeric variables (including poly variables
Line 1,410: Line 1,605:




<lang C>int a = 0;
<syntaxhighlight lang="c">int a = 0;
int b = 1;
int b = 1;
int c;
int c;
Line 1,421: Line 1,616:
if (!defined(c)) {puts("fourth test is true");} // This should print
if (!defined(c)) {puts("fourth test is true");} // This should print
if (str1) {puts("fifth test str1 is true");} // This should print
if (str1) {puts("fifth test str1 is true");} // This should print
if (str2) {puts("sixth test str2 is false");} // This should not print</lang>
if (str2) {puts("sixth test str2 is false");} // This should not print</syntaxhighlight>

=={{header|LiveCode}}==
=={{header|LiveCode}}==
true and the string "true" are both logical true, similarly for false and "false" being logical false.
true and the string "true" are both logical true, similarly for false and "false" being logical false.

=={{header|Logo}}==
=={{header|Logo}}==
Logo has predefined symbols for true and false (<code>"true</code> and <code>"false</code>), which are the values returned by predicates and required by logical operators and conditionals.
Logo has predefined symbols for true and false (<code>"true</code> and <code>"false</code>), which are the values returned by predicates and required by logical operators and conditionals.
<lang logo>print 1 < 0 ; false
<syntaxhighlight lang="logo">print 1 < 0 ; false
print 1 > 0 ; true
print 1 > 0 ; true
if "true [print "yes] ; yes
if "true [print "yes] ; yes
if not "false [print "no] ; no</lang>
if not "false [print "no] ; no</syntaxhighlight>
Unlike other lispy languages, there are no other implicit conversions.
Unlike other lispy languages, there are no other implicit conversions.
You must test explicitly for zero or empty collections.
You must test explicitly for zero or empty collections.
<lang logo>if equal? 0 ln 1 [print "zero]
<syntaxhighlight lang="logo">if equal? 0 ln 1 [print "zero]
if empty? [] [print "empty] ; empty list
if empty? [] [print "empty] ; empty list
if empty? "|| [print "empty] ; empty word</lang>
if empty? "|| [print "empty] ; empty word</syntaxhighlight>

=={{header|Lua}}==
=={{header|Lua}}==
All values in Lua other than <code>false</code> or <code>nil</code> are considered <code>true</code>:
All values in Lua other than <code>false</code> or <code>nil</code> are considered <code>true</code>:
<lang lua>if 0 then print "0" end -- This prints
<syntaxhighlight lang="lua">if 0 then print "0" end -- This prints
if "" then print"empty string" end -- This prints
if "" then print"empty string" end -- This prints
if {} then print"empty table" end -- This prints
if {} then print"empty table" end -- This prints
if nil then print"this won't print" end
if nil then print"this won't print" end
if true then print"true" end
if true then print"true" end
if false then print"false" end -- This does not print</lang>
if false then print"false" end -- This does not print</syntaxhighlight>

=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
True is -1 and False is 0 (double type), but any comparison return boolean. We can define boolean type variables.
True is -1 and False is 0 (double type), but any comparison return boolean. We can define boolean type variables.
Line 1,461: Line 1,652:




<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckBoolean {
Module CheckBoolean {
A=True
A=True
Line 1,492: Line 1,683:
Print str$(2, "\t\r\u\e;\t\r\u\e;\f\a\l\s\e")="true"
Print str$(2, "\t\r\u\e;\t\r\u\e;\f\a\l\s\e")="true"


</syntaxhighlight>
</lang>

=={{header|Maple}}==
=={{header|Maple}}==
The keywords "true" and "false" are the default boolean values.
The keywords "true" and "false" are the default boolean values.
Line 1,499: Line 1,689:
Expressions under assumptions may be evaluated logically using the <code>is</code> command.
Expressions under assumptions may be evaluated logically using the <code>is</code> command.
Types may be tested, resulting in boolean values, using the <code>type</code> command.
Types may be tested, resulting in boolean values, using the <code>type</code> command.

=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
True and False are the default boolean values.
True and False are the default boolean values.
To make any expression a boolean use the Boole[] function.
To make any expression a boolean use the Boole[] function.

=={{header|MATLAB}}==
=={{header|MATLAB}}==
The keywords "true" and "false" are the default boolean values.
The keywords "true" and "false" are the default boolean values.
Line 1,512: Line 1,700:
Sample Usage: (islogical() is a function that returns a boolean "1" if the input is a boolean, "0" otherwise)
Sample Usage: (islogical() is a function that returns a boolean "1" if the input is a boolean, "0" otherwise)


<lang MATLAB>>> islogical(true)
<syntaxhighlight lang="matlab">>> islogical(true)


ans =
ans =
Line 1,546: Line 1,734:
ans =
ans =


0</lang>
0</syntaxhighlight>

=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>is(1 < 2);
<syntaxhighlight lang="maxima">is(1 < 2);
/* true */
/* true */


Line 1,559: Line 1,746:


not false;
not false;
/* true */</lang>
/* true */</syntaxhighlight>

=={{header|Metafont}}==
=={{header|Metafont}}==
Metafont has the type <tt>boolean</tt>; a boolean variable can be <tt>true</tt> or <tt>false</tt>.
Metafont has the type <tt>boolean</tt>; a boolean variable can be <tt>true</tt> or <tt>false</tt>.
Using non boolean values (or expressions that do not evaluate to a boolean value) results in a recoverable error; by default, any non-boolean value is interpreted as false.
Using non boolean values (or expressions that do not evaluate to a boolean value) results in a recoverable error; by default, any non-boolean value is interpreted as false.

=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
Line 1,575: Line 1,760:
*empty string: <code>false</code>
*empty string: <code>false</code>
*boolean: no conversion performed
*boolean: no conversion performed

=={{header|MiniScript}}==
=={{header|MiniScript}}==
In MiniScript, numbers represent boolean values, with additional fuzzy logic for degrees of truth. Built-in constants `true` and `false` are simply aliases for 1 and 0, respectively.
In MiniScript, numbers represent boolean values, with additional fuzzy logic for degrees of truth. Built-in constants `true` and `false` are simply aliases for 1 and 0, respectively.


<lang MiniScript>boolTrue = true
<syntaxhighlight lang="miniscript">boolTrue = true
boolFalse = false
boolFalse = false


Line 1,589: Line 1,773:
kindaTrue = 0.4
kindaTrue = 0.4
print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue)
print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue)
print "mostlyTrue OR kindaTrue: " + (mostlyTrue or kindaTrue)</lang>
print "mostlyTrue OR kindaTrue: " + (mostlyTrue or kindaTrue)</syntaxhighlight>
{{out}}
{{out}}
<pre>boolTrue is true, and its value is: 1
<pre>boolTrue is true, and its value is: 1
Line 1,595: Line 1,779:
mostlyTrue AND kindaTrue: 0.32
mostlyTrue AND kindaTrue: 0.32
mostlyTrue OR kindaTrue: 0.88</pre>
mostlyTrue OR kindaTrue: 0.88</pre>

=={{header|Mirah}}==
=={{header|Mirah}}==
<lang mirah>import java.util.ArrayList
<syntaxhighlight lang="mirah">import java.util.ArrayList
import java.util.HashMap
import java.util.HashMap


Line 1,626: Line 1,809:
#puts 'FALSE is false' if !FALSE # ==> FALSE does not exist
#puts 'FALSE is false' if !FALSE # ==> FALSE does not exist


</syntaxhighlight>
</lang>

=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE boo;
<syntaxhighlight lang="modula2">MODULE boo;


IMPORT InOut;
IMPORT InOut;
Line 1,645: Line 1,827:
done := A > B
done := A > B
UNTIL done
UNTIL done
END boo.</lang>
END boo.</syntaxhighlight>

=={{header|Modula-3}}==
=={{header|Modula-3}}==
Similar to [[Ada]], Modula-3 has a built-in <tt>BOOLEAN</tt> type defined as
Similar to [[Ada]], Modula-3 has a built-in <tt>BOOLEAN</tt> type defined as
<lang modula3>TYPE BOOLEAN = {FALSE, TRUE}</lang>
<syntaxhighlight lang="modula3">TYPE BOOLEAN = {FALSE, TRUE}</syntaxhighlight>

=={{header|Monte}}==
=={{header|Monte}}==


Much like [[E]], Monte has built-in objects <tt>true</tt> and <tt>false</tt>, and a boolean [http://wiki.erights.org/wiki/Guard guard].
Much like [[E]], Monte has built-in objects <tt>true</tt> and <tt>false</tt>, and a boolean [http://wiki.erights.org/wiki/Guard guard].


<syntaxhighlight lang="monte">
<lang Monte>
def example(input :boolean):
def example(input :boolean):
if input:
if input:
return "Input was true!"
return "Input was true!"
return "Input was false."
return "Input was false."
</syntaxhighlight>
</lang>

=={{header|MUMPS}}==
=={{header|MUMPS}}==


Line 1,681: Line 1,860:
Newer implementations of the language may also support !! (exclusve or).
Newer implementations of the language may also support !! (exclusve or).
There is one unary boolean operator: ' (not).</p>
There is one unary boolean operator: ' (not).</p>

=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang nanoquery>a = true
<syntaxhighlight lang="nanoquery">a = true
b = false
b = false


Line 1,690: Line 1,868:
else if b
else if b
println "b is true"
println "b is true"
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>a is true</pre>
<pre>a is true</pre>

=={{header|Neko}}==
=={{header|Neko}}==


Line 1,701: Line 1,878:
is false, 0 or null. $istrue returning true if value is not false, not 0 and not null.
is false, 0 or null. $istrue returning true if value is not false, not 0 and not null.


<lang neko>/* boolean values */
<syntaxhighlight lang="neko">/* boolean values */
$print(true, "\n");
$print(true, "\n");
$print(false, "\n");
$print(false, "\n");
Line 1,727: Line 1,904:
} else {
} else {
$print("$istrue(1) tests false\n");
$print("$istrue(1) tests false\n");
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,739: Line 1,916:
$istrue(0) tests false
$istrue(0) tests false
$istrue(1) tests true</pre>
$istrue(1) tests true</pre>

=={{header|Nemerle}}==
=={{header|Nemerle}}==
In Nemerle, boolean values are held in variables of type '''bool''', and can be either '''true''' or '''false'''. Comparison expressions evaluate to boolean values as well.
In Nemerle, boolean values are held in variables of type '''bool''', and can be either '''true''' or '''false'''. Comparison expressions evaluate to boolean values as well.

=={{header|NetRexx}}==
=={{header|NetRexx}}==
NetRexx inherits boolean functionality directly from the [[Java]] virtual machine with the exception that the <code>true</code> and <code>false</code> keywords are not defined to the language.
NetRexx inherits boolean functionality directly from the [[Java]] virtual machine with the exception that the <code>true</code> and <code>false</code> keywords are not defined to the language.
Defining <code>true</code> and <code>false</code> variables can lead to name collisions during compilation so a simple expedient is to define boolean functions <code>isTrue</code>
Defining <code>true</code> and <code>false</code> variables can lead to name collisions during compilation so a simple expedient is to define boolean functions <code>isTrue</code>
and <code>isFalse</code> to return the appropriate values.
and <code>isFalse</code> to return the appropriate values.
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
options replace format comments java crossref savelog symbols nobinary


Line 1,765: Line 1,940:
method isFalse public static returns boolean
method isFalse public static returns boolean
return \isTrue
return \isTrue
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,778: Line 1,953:
0 is false
0 is false
</pre>
</pre>

=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>if true: echo "yes"
<syntaxhighlight lang="nim">if true: echo "yes"
if false: echo "no"
if false: echo "no"


# Other objects never represent true or false:
# Other objects never represent true or false:
if 2: echo "compile error"</lang>
if 2: echo "compile error"</syntaxhighlight>

=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
<lang oberon2>
<syntaxhighlight lang="oberon2">
VAR
VAR
a,b,c: BOOLEAN;
a,b,c: BOOLEAN;
Line 1,794: Line 1,967:
b := FALSE;
b := FALSE;
c := 1 > 2;
c := 1 > 2;
</syntaxhighlight>
</lang>

=={{header|Objeck}}==
=={{header|Objeck}}==
Objeck has a <tt>Bool</tt> type that is set to either <tt>true</tt> or <tt>false</tt>. By default boolean types are initialized to <tt>false</tt>. The boolean type also allows methods to be invoked, which perform simple conversions or print given values.
Objeck has a <tt>Bool</tt> type that is set to either <tt>true</tt> or <tt>false</tt>. By default boolean types are initialized to <tt>false</tt>. The boolean type also allows methods to be invoked, which perform simple conversions or print given values.

=={{header|Object Pascal}}==
=={{header|Object Pascal}}==
In addition to the <code>Boolean</code> type defined by standard [[#Pascal|Pascal]], object Pascal defines the types <code>byteBool</code>, <code>wordBool</code> and <code>longBool</code>, having a <code>sizeOf</code> one, two, or four bytes respectively.
In addition to the <code>Boolean</code> type defined by standard [[#Pascal|Pascal]], object Pascal defines the types <code>byteBool</code>, <code>wordBool</code> and <code>longBool</code>, having a <code>sizeOf</code> one, two, or four bytes respectively.
Line 1,807: Line 1,978:


''See also [[#Delphi|Delphi]] and [[#Free Pascal|Free Pascal]]''
''See also [[#Delphi|Delphi]] and [[#Free Pascal|Free Pascal]]''

=={{header|Objective-C}}==
=={{header|Objective-C}}==
Objective-C follows pretty much the same rules as C. In addition to C, Objective-C has a <code>BOOL</code> boolean type, with values <code>YES</code> for true and <code>NO</code> for false. Objective-C also adds several special types of pointers; for pointers to objects (values of type <code>id</code>), the <code>nil</code> pointer is false, everything else is true; for pointers to classes (values of type <code>Class</code>), the <code>Nil</code> pointer is false, everything else is true.
Objective-C follows pretty much the same rules as C. In addition to C, Objective-C has a <code>BOOL</code> boolean type, with values <code>YES</code> for true and <code>NO</code> for false. Objective-C also adds several special types of pointers; for pointers to objects (values of type <code>id</code>), the <code>nil</code> pointer is false, everything else is true; for pointers to classes (values of type <code>Class</code>), the <code>Nil</code> pointer is false, everything else is true.

=={{header|OCaml}}==
=={{header|OCaml}}==


OCaml defines a built-in data type <code>bool</code>, which has exactly two members, represented by the keywords <code>true</code> and <code>false</code>:
OCaml defines a built-in data type <code>bool</code>, which has exactly two members, represented by the keywords <code>true</code> and <code>false</code>:


<lang ocaml>type bool = false | true</lang>
<syntaxhighlight lang="ocaml">type bool = false | true</syntaxhighlight>


In addition to all the functionality of any other OCaml algebraic data type (e.g. [[pattern matching]]), and the functionality of any other OCaml data type (e.g. comparisons <code>false = false</code>, <code>false < true</code>, etc.), <code>bool</code> is also used in the guards in pattern matching (“<code>when</code>”) and <code>if</code> and <code>while</code> syntaxes.
In addition to all the functionality of any other OCaml algebraic data type (e.g. [[pattern matching]]), and the functionality of any other OCaml data type (e.g. comparisons <code>false = false</code>, <code>false < true</code>, etc.), <code>bool</code> is also used in the guards in pattern matching (“<code>when</code>”) and <code>if</code> and <code>while</code> syntaxes.


As with any other OCaml data type, there are no automatic conversions of other types to <code>bool</code>.
As with any other OCaml data type, there are no automatic conversions of other types to <code>bool</code>.

=={{header|Octave}}==
=={{header|Octave}}==
Octave uses <tt>true</tt> (1) and <tt>false</tt> (0). The class of a variable holding a boolean value is ''logical'', which however can be casted to a numeric class, so that <code>r = true; r * 2</code> gives 2 as result. Any non-zero value is interpreted as true, and 0 as false.
Octave uses <tt>true</tt> (1) and <tt>false</tt> (0). The class of a variable holding a boolean value is ''logical'', which however can be casted to a numeric class, so that <code>r = true; r * 2</code> gives 2 as result. Any non-zero value is interpreted as true, and 0 as false.

=={{header|Oforth}}==
=={{header|Oforth}}==
Oforth uses <tt>true</tt> (1) and <tt>false</tt> (0)
Oforth uses <tt>true</tt> (1) and <tt>false</tt> (0)


Any non-zero value is interpreted as true, and 0 as false.
Any non-zero value is interpreted as true, and 0 as false.

=={{header|Ol}}==
=={{header|Ol}}==


Line 1,836: Line 2,002:


p.s. Empty lists - '() - in conditionals is True.
p.s. Empty lists - '() - in conditionals is True.

=={{header|ooRexx}}==
=={{header|ooRexx}}==


<tt>.true</tt> or <tt>1</tt> are true, <tt>.false</tt> or <tt>0</tt> are false
<tt>.true</tt> or <tt>1</tt> are true, <tt>.false</tt> or <tt>0</tt> are false

=={{header|Order}}==
=={{header|Order}}==
Order supplies the keywords <code>8true</code> and <code>8false</code>. Other types are not supposed to automatically convert to any boolean value (in practice some may do so due to implementation quirks, but this is not reliable).
Order supplies the keywords <code>8true</code> and <code>8false</code>. Other types are not supposed to automatically convert to any boolean value (in practice some may do so due to implementation quirks, but this is not reliable).

=={{header|Oz}}==
=={{header|Oz}}==
<tt>true</tt> and <tt>false</tt> are the only boolean values. No other values are automatically converted to bool.
<tt>true</tt> and <tt>false</tt> are the only boolean values. No other values are automatically converted to bool.

=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Generally, false is 0 and true is nonzero. Certain other values also behave as false, like the vector [0]. Built-in boolean functions use 0 and 1 (but note that some functions like <code>ispower</code> are not boolean!).
Generally, false is 0 and true is nonzero. Certain other values also behave as false, like the vector [0]. Built-in boolean functions use 0 and 1 (but note that some functions like <code>ispower</code> are not boolean!).
Line 1,857: Line 2,019:
* A vector (t_VEC), column vector (t_COL), or matrix (t_MAT) is false if and only if all of its components are 0. Note that <code>[]</code> is thus false.
* A vector (t_VEC), column vector (t_COL), or matrix (t_MAT) is false if and only if all of its components are 0. Note that <code>[]</code> is thus false.
* t_QUAD, t_POLMOD, t_RFRAC
* t_QUAD, t_POLMOD, t_RFRAC

=={{header|Pascal}}==
=={{header|Pascal}}==
Pascal defines the type <code>Boolean</code> as a “special” enumeration type with exactly two elements:
Pascal defines the type <code>Boolean</code> as a “special” enumeration type with exactly two elements:
Line 1,867: Line 2,028:


''See also [[#Delphi|Delphi]], [[#Free Pascal|Free Pascal]], and [[#Object Pascal|Object Pascal]]''
''See also [[#Delphi|Delphi]], [[#Free Pascal|Free Pascal]], and [[#Object Pascal|Object Pascal]]''

=={{header|Perl}}==
=={{header|Perl}}==


<lang perl>my $x = 0.0;
<syntaxhighlight lang="perl">my $x = 0.0;
my $true_or_false = $x ? 'true' : 'false'; # false</lang>
my $true_or_false = $x ? 'true' : 'false'; # false</syntaxhighlight>
or
or
<lang perl>my $x = 1; # true
<syntaxhighlight lang="perl">my $x = 1; # true


my $true_or_false;
my $true_or_false;
Line 1,882: Line 2,042:
else {
else {
$true_or_false = 'false';
$true_or_false = 'false';
}</lang>
}</syntaxhighlight>
The values in Perl that are false are: <tt>0</tt> (as a number (including <tt>0.0</tt>), or as the string <tt>'0'</tt>, but '''not''' the string <tt>'0.0'</tt>), the empty string <tt><nowiki>''</nowiki></tt>, the empty list <tt>()</tt>, and <tt>undef</tt>. Everything else is true. See [http://perldoc.perl.org/perlsyn.html#Truth-and-Falsehood perlsyn].
The values in Perl that are false are: <tt>0</tt> (as a number (including <tt>0.0</tt>), or as the string <tt>'0'</tt>, but '''not''' the string <tt>'0.0'</tt>), the empty string <tt><nowiki>''</nowiki></tt>, the empty list <tt>()</tt>, and <tt>undef</tt>. Everything else is true. See [http://perldoc.perl.org/perlsyn.html#Truth-and-Falsehood perlsyn].


Line 1,889: Line 2,049:
Boolean comparison of zero against itself gives a value of one, but Perl uses short circuit evaluations, so any true or false value may be returned from a boolean expression:
Boolean comparison of zero against itself gives a value of one, but Perl uses short circuit evaluations, so any true or false value may be returned from a boolean expression:


<lang perl>print (7 && 2); # 2, rather than 1(true)
<syntaxhighlight lang="perl">print (7 && 2); # 2, rather than 1(true)
print (2 && 7); # 7, rather than 1(true)
print (2 && 7); # 7, rather than 1(true)
print (7 xor 2); # empty string, rather than 0(false)
print (7 xor 2); # empty string, rather than 0(false)
print ('apples' && 'pears'); # pears, rather than 1(true)
print ('apples' && 'pears'); # pears, rather than 1(true)
print ('apples' xor 'pears'); # empty string, rather than 0(false)</lang>
print ('apples' xor 'pears'); # empty string, rather than 0(false)</syntaxhighlight>


=== Objects ===
=== Objects ===
Line 1,901: Line 2,061:
=== There are no keywords for true and false ===
=== There are no keywords for true and false ===


Perl has no builtin "true" or "false" keywords. This is a caveat, because true and false are bareword strings and evaluate to true:
Perl has no builtin "true" or "false" keywords. An old trick of using them as bareword strings is strongly discouraged in modern Perl.

<lang perl># This does not work
# true and false are not special so will be treated as bareword strings
if (true) { print "true is true\n" }; # This prints
if (false) { print "false is true\n" }; # So does this
if (spongebob) { print "spongebob is true\n" }; # A bareword string</lang>


=== Special cases ===
=== Special cases ===


As a special case, literal <tt>1</tt>s and <tt>0</tt>s will never cause a "Useless use of a constant in void context" warning. Another special case worth pointing out here is that the string <tt>'0 but true'</tt> won't provoke a warning if it's used as a number.
As a special case, literal <tt>1</tt>s and <tt>0</tt>s will never cause a "Useless use of a constant in void context" warning. Another special case worth pointing out here is that the string <tt>'0 but true'</tt> won't provoke a warning if it's used as a number.

=={{header|Phix}}==
=={{header|Phix}}==
Zero is false, any other number is true. Attempting to use a string or sequence as a boolean is assumed to be a programming logic blunder and causes a fatal run-time error.
Zero is false, any other number is true. Attempting to use a string or sequence as a boolean is assumed to be a programming logic blunder and causes a fatal run-time error.


Conditions such as <code>if length(s) then</code> are permitted, but the more explicit <code>if length(s)!=0 then</code> is preferred. Comparison operators evaluate to 1(true) or 0(false).
Conditions such as <code>if length(s) then</code> are permitted, but the more explicit <code>if length(s)!=0 then</code> is generally preferred, and conversely, <code>if flag then</code> is to be preferred over <code>if flag=true then</code>.
Comparison operators evaluate to 1(true) or 0(false).
A boolean test is inverted by preceding it with the keyword <code>not</code>. The null character ('\0') is considered false, all other characters are deemed true.
A boolean test is inverted by preceding it with the keyword <code>not</code>. The null character ('\0') is considered false, all other characters are deemed true.
The builtin constants TRUE/FALSE and their aliases True/true/False/false may also be used.
The builtin constants TRUE/FALSE and their aliases True/true/False/false may also be used.


There is however a gotcha in JavaScript, and hence pwa/p2js, in that <b>true !== 1</b> and <b>false !== 0</b>. In almost all other respects, true is 1 and false is 0, for instance 1+true evaluates to 2, just like desktop/Phix. It is only direct comparison for equality of booleans and numbers using an infix operator which fails, and I suppose you could argue that is a programming logic blunder, by which I mean in a particular source file of a specific application, rather than in the (Phix ''or'' JavaScript) programming language definition. There is no such issue with equal() and compare(), which pwa/p2js automatically maps to when needed, that is except for bool vs number, which is difficult because in desktop/Phix those <i>are the same thing</i>. Thankfully, there are very few places anyone ever actually compares bools against 0 and 1 using an infix operator.

The following example illustrates, and also emphasies the subtlety of the issue (no difference whatsoever if c, d, e, f are defined as bool):
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">3</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">==</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span> <span style="color: #000080;font-style:italic;">-- fine</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">==</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span> <span style="color: #000080;font-style:italic;">-- oops</span>
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">==</span><span style="color: #004600;">true</span><span style="color: #0000FF;">),</span> <span style="color: #000080;font-style:italic;">-- fine</span>
<span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">equal</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- fine, ditto equal(c,true)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d==2:%5t(%d) ==1:%5t, eq1:%5t, ==true:%5t\n"</span><span style="color: #0000FF;">,</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">e</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">--
-- output on desktop/Phix: 1==2:false(0) ==1:false, eq1:false, ==true:false
-- 2==2: true(1) ==1: true, eq1: true, ==true: true
-- 3==2:false(0) ==1:false, eq1:false, ==true:false
--
-- output on pwa/p2js: 1==2:false(0) ==1:false, eq1:false, ==true:false
-- 2==2: true(1) ==1:<font color="#FF0000">false</font>, eq1: true, ==true: true
-- 3==2:false(0) ==1:false, eq1:false, ==true:false
--</span>
<!--</syntaxhighlight>-->
=={{header|PHP}}==
=={{header|PHP}}==
The values in PHP that are false are: <tt>FALSE</tt>, <tt>NULL</tt>, the number <tt>0</tt> (as an integer <tt>0</tt>, float <tt>0.0</tt>, or string <tt>'0'</tt>, but '''not''' the string <tt>"0.0"</tt>), the empty string <tt>""</tt>, the empty array <tt>array()</tt>, and "SimpleXML objects created from empty tags"(?).
The values in PHP that are false are: <tt>FALSE</tt>, <tt>NULL</tt>, the number <tt>0</tt> (as an integer <tt>0</tt>, float <tt>0.0</tt>, or string <tt>'0'</tt>, but '''not''' the string <tt>"0.0"</tt>), the empty string <tt>""</tt>, the empty array <tt>array()</tt>, and "SimpleXML objects created from empty tags"(?).
Line 1,925: Line 2,102:
Everything else is true. The keyword <tt>TRUE</tt> exists.
Everything else is true. The keyword <tt>TRUE</tt> exists.
[http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting]
[http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting]
=={{header|Picat}}==
Picat has the built-in <code>true/0</code> for true (it always succeeds) and <code>false/0</code> (or <code>fail/0</code>) for false. <code>false/0</code> (/<code>fail/0</code>) can be used to generate other solutions through backtracking.


<syntaxhighlight lang="picat">go ?=>
member(N,1..5),
println(N),
fail, % or false/0 to get other solutions
nl.
go => true.</syntaxhighlight>

{{out}}
<pre>1
2
3
4
5</pre>

In the Picat shell, truth is represented as "yes" and false as "no".
<pre>Picat> 2==2

yes

Picat> 2==3

no</pre>
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Like in all Lisps, the symbol 'NIL' denotes "false", any other value "true". PicoLisp also uses NIL as the empty list, so the empty list is false.
Like in all Lisps, the symbol 'NIL' denotes "false", any other value "true". PicoLisp also uses NIL as the empty list, so the empty list is false.
Line 1,932: Line 2,133:
value is available in the given context. Note that 'NIL' and 'T' are written in
value is available in the given context. Note that 'NIL' and 'T' are written in
uppercase letters (PicoLisp is case-sensitive).
uppercase letters (PicoLisp is case-sensitive).

=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>
<syntaxhighlight lang="pike">
> 0;
> 0;
(3) Result: 0
(3) Result: 0
Line 1,948: Line 2,148:
(9) Result: 1
(9) Result: 1
>
>
</syntaxhighlight>
</lang>

=={{header|PL/I}}==
=={{header|PL/I}}==
True is <code>'1'b</code> and false is <code>'0'b</code>.
True is <code>'1'b</code> and false is <code>'0'b</code>.
<lang pli>Declare x bit(1);
<syntaxhighlight lang="pli">Declare x bit(1);
x='1'b; /* True */
x='1'b; /* True */
x='0'b; /* False */</lang>
x='0'b; /* False */</syntaxhighlight>
Using the macro facility one can define reasonable symbols for true and false
Using the macro facility one can define reasonable symbols for true and false
<lang pli>*process source attributes xref macro or(!);
<syntaxhighlight lang="pli">*process source attributes xref macro or(!);
tf: proc options(main);
tf: proc options(main);
%Dcl true char; %true='''1''b';
%Dcl true char; %true='''1''b';
Line 1,966: Line 2,165:
Else
Else
Put Skip List('false was recognized');
Put Skip List('false was recognized');
End;</lang>
End;</syntaxhighlight>
{{out}}
{{out}}
<pre>That's true
<pre>That's true
false was recognized</pre>
false was recognized</pre>

=={{header|PL/M}}==
=={{header|PL/M}}==


In PL/M, even numbers are falsy and odd numbers are truthy. That is to say, conditional expressions test only the low bit of the value.
In PL/M, even numbers are falsy and odd numbers are truthy. That is to say, conditional expressions test only the low bit of the value.


<lang pli>IF 0 THEN /* THIS WON'T RUN */;
<syntaxhighlight lang="pli">IF 0 THEN /* THIS WON'T RUN */;
IF 1 THEN /* THIS WILL */;
IF 1 THEN /* THIS WILL */;
IF 2 THEN /* THIS WON'T */;
IF 2 THEN /* THIS WON'T */;
IF 3 THEN /* THIS WILL */;</lang>
IF 3 THEN /* THIS WILL */;</syntaxhighlight>


Canonically, false is represented by <code>0</code> (all bits clear), and true by <code>0FFH</code> (all bits set). These are the values that conditional operators (like <code>=</code>) return.
Canonically, false is represented by <code>0</code> (all bits clear), and true by <code>0FFH</code> (all bits set). These are the values that conditional operators (like <code>=</code>) return.


<lang pli>DECLARE A BYTE;
<syntaxhighlight lang="pli">DECLARE A BYTE;
A = 4 < 5;
A = 4 < 5;
/* A IS NOW 0FFH */</lang>
/* A IS NOW 0FFH */</syntaxhighlight>


Boolean literals are not included by default, but it is not uncommon for programmers to define them by hand:
Boolean literals are not included by default, but it is not uncommon for programmers to define them by hand:


<lang pli>DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';</lang>
<syntaxhighlight lang="pli">DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';</syntaxhighlight>

=={{header|Plain English}}==
=={{header|Plain English}}==
Boolean values are called flags. The flag literals are <code>yes</code> and <code>no</code>. You can <code>set</code> and <code>clear</code> flags.
Boolean values are called flags. The flag literals are <code>yes</code> and <code>no</code>. You can <code>set</code> and <code>clear</code> flags.

=={{header|Pony}}==
=={{header|Pony}}==
Boolean values are <code>true</code> and <code>false</code>. Conditions must have type Bool, i.e. they are always true or false.
Boolean values are <code>true</code> and <code>false</code>. Conditions must have type Bool, i.e. they are always true or false.

=={{header|PostScript}}==
=={{header|PostScript}}==


Predefined constants are:
Predefined constants are:
<lang postscript>true
<syntaxhighlight lang="postscript">true
false</lang>
false</syntaxhighlight>

=={{header|PowerShell}}==
=={{header|PowerShell}}==
Two automatic variables exist for this purpose:
Two automatic variables exist for this purpose:
<lang powershell>$true
<syntaxhighlight lang="powershell">$true
$false</lang>
$false</syntaxhighlight>
However, nearly everything can be converted to a boolean value, as detailed in the following list:
However, nearly everything can be converted to a boolean value, as detailed in the following list:
* any non-zero number evaluates to '''true''', zero evaluates to '''false'''
* any non-zero number evaluates to '''true''', zero evaluates to '''false'''
Line 2,013: Line 2,207:
* any array with more than one item evaluates to '''true'''
* any array with more than one item evaluates to '''true'''
* a reference to any object evaluates to '''true''', <code>$null</code> evaluates to '''false'''
* a reference to any object evaluates to '''true''', <code>$null</code> evaluates to '''false'''

=={{header|Python}}==
=={{header|Python}}==
Python has a boolean data type with the only two possible values denoted by <code>True</code> and <code>False</code>.
Python has a boolean data type with the only two possible values denoted by <code>True</code> and <code>False</code>.
Line 2,026: Line 2,219:


'''Some examples:'''
'''Some examples:'''
<lang python>>>> True
<syntaxhighlight lang="python">>>> True
True
True
>>> not True
>>> not True
Line 2,064: Line 2,257:
False
False
>>> bool("False")
>>> bool("False")
True</lang>
True</syntaxhighlight>

=={{header|Quackery}}==
=={{header|Quackery}}==
{{trans|Forth}}
{{trans|Forth}}
In conditionals, zero is false, non-zero is true. There are predefined words for the canonical forms, <code>false</code> returns zero and <code>true</code> returns 1.
In conditionals, zero is false, non-zero is true. There are predefined words for the canonical forms, <code>false</code> returns zero and <code>true</code> returns 1.

=={{header|R}}==
=={{header|R}}==
Similarly to Octave, R uses <tt>TRUE</tt> and <tt>FALSE</tt>, kept in variable of class logical, which is silently casted to 1 (TRUE) or 0 (FALSE) if used as numeric value. The opposite is also true: the value 0 can be used as FALSE, and non-zero numbers as TRUE.
Similarly to Octave, R uses <tt>TRUE</tt> and <tt>FALSE</tt>, kept in variable of class logical, which is silently casted to 1 (TRUE) or 0 (FALSE) if used as numeric value. The opposite is also true: the value 0 can be used as FALSE, and non-zero numbers as TRUE.


The values T and F are given the values TRUE and FALSE respectively (for compatibility with S-Plus), though these may be changed to other values by the user.
The values T and F are given the values TRUE and FALSE respectively (for compatibility with S-Plus), though these may be changed to other values by the user.

=={{header|Racket}}==
=={{header|Racket}}==


Racket has the standard Scheme Boolean values <tt>#t</tt> and <tt>#f</tt>, and will also accept <tt>#true</tt> and <tt>#false</tt>. This is a literal syntax, so it can be used anywhere including in quoted positions. There are also bindings for <tt>true</tt> and <tt>false</tt> (but of course when these are quoted, the result is plain symbols). Like other Scheme descendants, many conditional constructs treat any non-false value as "truthy." So, for instance,
Racket has the standard Scheme Boolean values <tt>#t</tt> and <tt>#f</tt>, and will also accept <tt>#true</tt> and <tt>#false</tt>. This is a literal syntax, so it can be used anywhere including in quoted positions. There are also bindings for <tt>true</tt> and <tt>false</tt> (but of course when these are quoted, the result is plain symbols). Like other Scheme descendants, many conditional constructs treat any non-false value as "truthy." So, for instance,


<lang Racket>(cond ([(< 4 3) 'apple]
<syntaxhighlight lang="racket">(cond ([(< 4 3) 'apple]
['bloggle 'pear]
['bloggle 'pear]
[else 'nectarine])</lang>
[else 'nectarine])</syntaxhighlight>


... evaluates to <tt>'pear</tt>, because <tt>'bloggle</tt> is not false.
... evaluates to <tt>'pear</tt>, because <tt>'bloggle</tt> is not false.

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
Line 2,091: Line 2,280:
Raku provides an enumeration <code>Bool</code> with two values, <code>True</code> and <code>False</code>. Values of enumerations can be used as ordinary values or as mixins:
Raku provides an enumeration <code>Bool</code> with two values, <code>True</code> and <code>False</code>. Values of enumerations can be used as ordinary values or as mixins:


<lang perl6>my Bool $crashed = False;
<syntaxhighlight lang="raku" line>my Bool $crashed = False;
my $val = 0 but True;</lang>
my $val = 0 but True;</syntaxhighlight>

For a discussion of Boolean context (i.e. how Raku decides whether something is true or false), see [http://perlcabal.org/syn/S02.html#Context Synopsis 2].


For a discussion of Boolean context (how Raku decides whether something is True or False): https://docs.raku.org/language/contexts#index-entry-Boolean_context.
=={{header|Raven}}==
=={{header|Raven}}==
Raven considers 0 as <code>FALSE</code>, -1 as <code>TRUE</code>
Raven considers 0 as <code>FALSE</code>, -1 as <code>TRUE</code>
<lang Raven>TRUE print
<syntaxhighlight lang="raven">TRUE print
FALSE print
FALSE print
2 1 > print # TRUE (-1)
2 1 > print # TRUE (-1)
3 2 < print # FALSE (0)
3 2 < print # FALSE (0)
42 FALSE != # TRUE (-1)</lang>
42 FALSE != # TRUE (-1)</syntaxhighlight>

=={{header|REBOL}}==
=={{header|REBOL}}==
REBOL uses values of type '''logic!''' to represent boolean values. A boolean value can be 'true' or 'false', which also happen to be understood as predefined constants. Other constants are also provided to improve program readability:
REBOL uses values of type '''logic!''' to represent boolean values. A boolean value can be 'true' or 'false', which also happen to be understood as predefined constants. Other constants are also provided to improve program readability:
Line 2,121: Line 2,308:


As the last true value implies, pretty much any other type will evaluate to true. This is important to remember if you're used to a language where the value "0" is considered to be false -- in REBOL, it's true.
As the last true value implies, pretty much any other type will evaluate to true. This is important to remember if you're used to a language where the value "0" is considered to be false -- in REBOL, it's true.

=={{header|ReScript}}==
=={{header|ReScript}}==


Line 2,127: Line 2,313:


ReScript's true/false compiles into a JavaScript true/false.
ReScript's true/false compiles into a JavaScript true/false.

=={{header|Retro}}==
=={{header|Retro}}==
Zero is false and non-zero is true. Comparison functions return '''-1''' for true and '''0''' for false.
Zero is false and non-zero is true. Comparison functions return '''-1''' for true and '''0''' for false.

=={{header|REXX}}==
=={{header|REXX}}==
The REXX language enforces the values for &nbsp; ''true'' &nbsp; and &nbsp; ''false'', &nbsp; only the two values are valid:
The REXX language enforces the values for &nbsp; ''true'' &nbsp; and &nbsp; ''false'', &nbsp; only the two values are valid:
Line 2,149: Line 2,333:


===simplistic===
===simplistic===
<lang rexx> true = 1
<syntaxhighlight lang="rexx"> true = 1
false = 0</lang>
false = 0</syntaxhighlight>


===spruced up===
===spruced up===
Some programmers like to "spruce up" such a simple assignment:
Some programmers like to "spruce up" such a simple assignment:
<lang rexx>true = (1=1)
<syntaxhighlight lang="rexx">true = (1=1)
false = (1=0)</lang>
false = (1=0)</syntaxhighlight>


===more exactitudeness===
===more exactitudeness===
<lang rexx>true = (1==1)
<syntaxhighlight lang="rexx">true = (1==1)
false = (1==0)</lang>
false = (1==0)</syntaxhighlight>


===oblique===
===oblique===
<lang rexx>true = (1==1)
<syntaxhighlight lang="rexx">true = (1==1)
false = \true</lang>
false = \true</syntaxhighlight>
[The parentheses aren't necessary in all of the above versions.]
[The parentheses aren't necessary in all of the above versions.]
<br><br>Some REXX interpreters allow the &nbsp; ''NOT'' &nbsp; (<code>¬</code>) character for negation:
<br><br>Some REXX interpreters allow the &nbsp; ''NOT'' &nbsp; (<code>¬</code>) character for negation:
<lang rexx>false = ¬true</lang>
<syntaxhighlight lang="rexx">false = ¬true</syntaxhighlight>


===esoteric===
===esoteric===
<lang rexx>true = 1984 = 1984
<syntaxhighlight lang="rexx">true = 1984 = 1984
false = 'war' = 'peace'
false = 'war' = 'peace'
false = 'freedom' = 'slavery'
false = 'freedom' = 'slavery'
false = 'ignorance' = 'strength'</lang>
false = 'ignorance' = 'strength'</syntaxhighlight>
Of course, in Orwellian terms, the above &nbsp; '''false''' &nbsp; statements are &nbsp; '''true''', &nbsp; but REXX isn't an Eric Arthur Blair reader.
Of course, in Orwellian terms, the above &nbsp; '''false''' &nbsp; statements are &nbsp; '''true''', &nbsp; but REXX isn't an Eric Arthur Blair reader.
<br><br>
<br><br>

=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
x = True
x = True
y = False
y = False
Line 2,183: Line 2,366:
see "x or y : " + (x or y) + nl
see "x or y : " + (x or y) + nl
see "not x : " + (not x) + nl
see "not x : " + (not x) + nl
</syntaxhighlight>
</lang>
=={{header|Rockstar}}==
There are several synonyms for true and false. These include yes and no, or right and wrong. Therefore, to make a variable called Alice true and a variable called Bob false, you can write this.
<syntaxhighlight lang="rockstar">Alice was right.
Bob was wrong.</syntaxhighlight>

=={{header|RPL}}==
There is no boolean variable type in RPL. Boolean values are real numbers, zero meaning 'FALSE' and any other value meaning 'TRUE'; built-in boolean operators and functions always return 1 for TRUE.
RPL users have also access to boolean registers named flags, identified by a number, that can be cleared, set or tested.
{{works with|Halcyon Calc|4.2.7}}
1 == 1
1 == 2
≪ IF 42 THEN "TRUE" ELSE "FALSE" END ≫ EVAL
14 CF 14 FS?
14 SF 14 FS?
{{out}}
<pre>
5: 1
4: 0
3: "TRUE"
2: 0
1: 1
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
Line 2,194: Line 2,399:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>
<syntaxhighlight lang="rust">
fn main() {
fn main() {
// Rust contains a single boolean type: `bool`, represented by the keywords `true` and `false`.
// Rust contains a single boolean type: `bool`, represented by the keywords `true` and `false`.
Line 2,210: Line 2,415:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,216: Line 2,421:
bar is false.
bar is false.
</pre>
</pre>

=={{header|Sather}}==
=={{header|Sather}}==
The BOOL type can be <code>true</code> or <code>false</code>. Sather never implicitly does casting of a type in another, so numeric value or other types cannot be used (implicitly) as boolean value; nonetheless an explicit "cast" can be done:
The BOOL type can be <code>true</code> or <code>false</code>. Sather never implicitly does casting of a type in another, so numeric value or other types cannot be used (implicitly) as boolean value; nonetheless an explicit "cast" can be done:


<lang sather>v:BOOL := true; -- ok
<syntaxhighlight lang="sather">v:BOOL := true; -- ok
i:INT := 1;
i:INT := 1;
v := 1; -- wrong
v := 1; -- wrong
Line 2,226: Line 2,430:
-- BUT
-- BUT
v := 1.bool; -- ok
v := 1.bool; -- ok
if i.bool then ... end; -- ok</lang>
if i.bool then ... end; -- ok</syntaxhighlight>

In this case, <code>0.bool</code> is false, and <code>n.bool</code> with n not equal to 0 is true.
In this case, <code>0.bool</code> is false, and <code>n.bool</code> with n not equal to 0 is true.

=={{header|S-BASIC}}==
Although S-BASIC has no explicit boolean data type, it allows integer,
real, fixed, string, and character variables to hold the results of boolean operations and to represent true and false conditions in IF, WHILE, and REPEAT statements. For types real.double, real, and fixed, a value of zero is false, and any non-zero value is true. For integers, the value 0 is treated as false, while -1 (or FFFFH), the bit-wise negation of zero, is treated as true.
For characters and strings, 'Y', 'y', 'T', and 't' are treated as true,
while 'N', 'n', 'F', and 'f' are treated as false. (For strings, only the first character is considered.) For convenience, the $CONSTANT compiler directive can be used to provide values for "true" and "false".
<syntaxhighlight lang = "BASIC">
$constant true = 0FFFFH
$constant false = 0

var a, another = char
var b, adult, age = integer
var c = real

repeat
begin
input "Applicant's age in years"; age
adult = (age >= 18)
if adult then
print "Applicant has full access"
else
print "Applicant has restricted access"
input "Do another (y/n)"; another
end
until not another

a = (2 > 3)
b = (2 > 3)
c = (2 > 3)
print "2 > 3 as char: "; a
print "2 > 3 as int : "; b
print "not (2 > 3) : "; not b
print "2 > 3 as real: "; c
print "not (2 > 3) : "; not c
end
</syntaxhighlight>
{{out}}
<pre>
Applicant's age in years? 19
Applicant has full access
Do another (y/n)? n
2 > 3 as char: F
2 > 3 as int : 0
not (2 > 3) :-1
2 > 3 as real: 0
not (2 > 3) :-1
</pre>


=={{header|Scala}}==
=={{header|Scala}}==
Booleans in Scala are given by the literals <code>true</code> and <code>false</code>, case sensitive, which are the only instances of the class <code>Boolean</code>.
Booleans in Scala are given by the literals <code>true</code> and <code>false</code>, case sensitive, which are the only instances of the class <code>Boolean</code>.

=={{header|Scheme}}==
=={{header|Scheme}}==
The only value in Scheme that is false is <tt>#f</tt>.
The only value in Scheme that is false is <tt>#f</tt>.


Everything else (including the empty list, unlike Lisp) is true. The constant <tt>#t</tt> represents the canonical true value.
Everything else (including the empty list, unlike Lisp) is true. The constant <tt>#t</tt> represents the canonical true value.

=={{header|Seed7}}==
=={{header|Seed7}}==
Seed7 defines the type <tt>boolean</tt>. The only values of <tt>boolean</tt> are <tt>TRUE</tt> and <tt>FALSE</tt>. There are no automatic conversions from any other types into <tt>boolean</tt>, and it is a compile-time error to use any type other than <tt>boolean</tt> in a place that expects a <tt>boolean</tt> (e.g. if-statement condition, while-statement condition, operand of a logical operator, etc.).
Seed7 defines the type <tt>boolean</tt>. The only values of <tt>boolean</tt> are <tt>TRUE</tt> and <tt>FALSE</tt>. There are no automatic conversions from any other types into <tt>boolean</tt>, and it is a compile-time error to use any type other than <tt>boolean</tt> in a place that expects a <tt>boolean</tt> (e.g. if-statement condition, while-statement condition, operand of a logical operator, etc.).

=={{header|Self}}==
=={{header|Self}}==


Self has two objects, ''true'' and ''false''.
Self has two objects, ''true'' and ''false''.

=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
True, Yes, and On are true; False, No, Off and Empty (an empty string) are false.
True, Yes, and On are true; False, No, Off and Empty (an empty string) are false.
<lang sensetalk>repeat with each item of [True, False, Yes, No, On, Off, ""]
<syntaxhighlight lang="sensetalk">repeat with each item of [True, False, Yes, No, On, Off, ""]
put it & " is " & (it is true)
put it & " is " & (it is true)
end repeat
end repeat
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,264: Line 2,511:
=={{header|Sidef}}==
=={{header|Sidef}}==
Sidef defines the ''true'' and ''false'' boolean values, which are part of the ''Bool'' type.
Sidef defines the ''true'' and ''false'' boolean values, which are part of the ''Bool'' type.
<lang ruby>var t = true;
<syntaxhighlight lang="ruby">var t = true;
var f = false;</lang>
var f = false;</syntaxhighlight>


In conditional expressions, anything that evaluates to zero or nothing is considered ''false'', including empty arrays and empty hashes.
In conditional expressions, anything that evaluates to zero or nothing is considered ''false'', including empty arrays and empty hashes.
<lang ruby>if (0 || "0" || false || nil || "" || [] || :()) {
<syntaxhighlight lang="ruby">if (0 || "0" || false || nil || "" || [] || :()) {
say "true"
say "true"
} else {
} else {
say "false";
say "false";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>false</pre>
<pre>false</pre>

=={{header|Simula}}==
=={{header|Simula}}==
Simula has <tt>true</tt> and <tt>false</tt> keywords, representing the only values of type <tt>boolean</tt>. There are no automatic conversions from any other types into <tt>boolean</tt>, and it is a compile-time error to use any type other than <tt>boolean</tt> in a place that expects a <tt>boolean</tt> (e.g. if-statement condition, while-statement condition, operand of a logical operator, etc.).
Simula has <tt>true</tt> and <tt>false</tt> keywords, representing the only values of type <tt>boolean</tt>. There are no automatic conversions from any other types into <tt>boolean</tt>, and it is a compile-time error to use any type other than <tt>boolean</tt> in a place that expects a <tt>boolean</tt> (e.g. if-statement condition, while-statement condition, operand of a logical operator, etc.).

=={{header|Slate}}==
=={{header|Slate}}==
Use <tt>True</tt> or <tt>False</tt>.
Use <tt>True</tt> or <tt>False</tt>.

=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Use "true" and "false".
Use "true" and "false".
<br>Smalltalk uses the Boolean class, which has two subclasses (True and False). <tt>true</tt> and <tt>false</tt> are singleton instances of those classes. E.g. an expression like <tt>5 = 5</tt> returns <tt>true</tt>.
<br>Smalltalk uses the Boolean class, which has two subclasses (True and False). <tt>true</tt> and <tt>false</tt> are singleton instances of those classes. E.g. an expression like <tt>5 = 5</tt> returns <tt>true</tt>.

=={{header|SNUSP}}==
=={{header|SNUSP}}==
Zero is false and non-zero is true, as used by the sole skip-if-zero operator ('''?''').
Zero is false and non-zero is true, as used by the sole skip-if-zero operator ('''?''').
<lang snusp>$!/?\=false= + =true=#
<syntaxhighlight lang="snusp">$!/?\=false= + =true=#
\-/</lang>
\-/</syntaxhighlight>

=={{header|SPL}}==
=={{header|SPL}}==
In SPL zero is false, any other value is true.
In SPL zero is false, any other value is true.

=={{header|Standard ML}}==
=={{header|Standard ML}}==


Standard ML defines a top-level data type <code>bool</code>, which has exactly two members, <code>true</code> and <code>false</code>:
Standard ML defines a top-level data type <code>bool</code>, which has exactly two members, <code>true</code> and <code>false</code>:


<lang sml>datatype bool = false | true</lang>
<syntaxhighlight lang="sml">datatype bool = false | true</syntaxhighlight>


In addition to all the functionality of any other Standard ML algebraic data type (e.g. [[pattern matching]], equality <code>false = false</code>), <code>bool</code> is also used in <code>if</code> and <code>while</code> syntaxes.
In addition to all the functionality of any other Standard ML algebraic data type (e.g. [[pattern matching]], equality <code>false = false</code>), <code>bool</code> is also used in <code>if</code> and <code>while</code> syntaxes.


As with any other Standard ML data type, there are no automatic conversions of other types to bool.
As with any other Standard ML data type, there are no automatic conversions of other types to bool.

=={{header|Stata}}==
=={{header|Stata}}==
Stata uses the values 0 for "false" and 1 for "true". In expressions involving boolean operators, any nonzero numeric value (including missing values) is considered true.
Stata uses the values 0 for "false" and 1 for "true". In expressions involving boolean operators, any nonzero numeric value (including missing values) is considered true.

=={{header|Swift}}==
=={{header|Swift}}==
Swift defines a built-in data type <code>Bool</code>, which has two values, represented by the keywords <code>true</code> and <code>false</code>. There is no conversion between booleans and other data types. Conditionals require a type that conforms to the <code>BooleanType</code> protocol, which provides a conversion to <code>Bool</code> for that type; types that conform include <code>Bool</code> and some other types.
Swift defines a built-in data type <code>Bool</code>, which has two values, represented by the keywords <code>true</code> and <code>false</code>. There is no conversion between booleans and other data types. Conditionals require a type that conforms to the <code>BooleanType</code> protocol, which provides a conversion to <code>Bool</code> for that type; types that conform include <code>Bool</code> and some other types.

=={{header|Tcl}}==
=={{header|Tcl}}==
;True values:
;True values:
Line 2,317: Line 2,555:
Any of these values may be abbreviated, and mixed-case spellings are also acceptable. [http://www.tcl.tk/man/tcl8.5/TclLib/GetInt.htm]
Any of these values may be abbreviated, and mixed-case spellings are also acceptable. [http://www.tcl.tk/man/tcl8.5/TclLib/GetInt.htm]
Any other value gives an error. In an interactive tclsh session:
Any other value gives an error. In an interactive tclsh session:
<lang tcl>% if {""} then {puts true} else {puts false}
<syntaxhighlight lang="tcl">% if {""} then {puts true} else {puts false}
expected boolean value but got ""</lang>
expected boolean value but got ""</syntaxhighlight>


Test for the boolean value of a string can be stuff like
Test for the boolean value of a string can be stuff like
<lang tcl>if {[string is false -strict $string]} ...</lang>
<syntaxhighlight lang="tcl">if {[string is false -strict $string]} ...</syntaxhighlight>
which will test for "no" or "NO" or "0" or "False" or ...
which will test for "no" or "NO" or "0" or "False" or ...

=={{header|Trith}}==
=={{header|Trith}}==
The boolean constants are ''true'' and ''false''. In a conditional context, the only false values are ''false'' and ''nil'' -- every other value is true.
The boolean constants are ''true'' and ''false''. In a conditional context, the only false values are ''false'' and ''nil'' -- every other value is true.



=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==


Line 2,342: Line 2,576:
In the following example, after running the test command, the then syntactical component runs the optional branch if an exitcode is of zero determined:
In the following example, after running the test command, the then syntactical component runs the optional branch if an exitcode is of zero determined:


<lang sh>if
<syntaxhighlight lang="sh">if
echo 'Looking for file' # This is the evaluation block
echo 'Looking for file' # This is the evaluation block
test -e foobar.fil # The exit code from this statement determines whether the branch runs
test -e foobar.fil # The exit code from this statement determines whether the branch runs
Line 2,349: Line 2,583:
echo 'I am going to delete it'
echo 'I am going to delete it'
rm foobar.fil
rm foobar.fil
fi</lang>
fi</syntaxhighlight>


In some later shells, the values ''true'' and ''false'' are defined, respectively, as a return code of 0 and a return code of greater-than zero. While there are built-in functions for each of these values, booleans are most commonly the result of a test or a process termination.
In some later shells, the values ''true'' and ''false'' are defined, respectively, as a return code of 0 and a return code of greater-than zero. While there are built-in functions for each of these values, booleans are most commonly the result of a test or a process termination.
Line 2,356: Line 2,590:
{{works with|ksh}}
{{works with|ksh}}


<lang Bash>true && echo "true" || echo "false"</lang>
<syntaxhighlight lang="bash">true && echo "true" || echo "false"</syntaxhighlight>

=={{header|Ursa}}==
=={{header|Ursa}}==
Ursa has the boolean data type which can be declared using the declare (or decl) function.
Ursa has the boolean data type which can be declared using the declare (or decl) function.
<lang ursa>decl boolean bool</lang>
<syntaxhighlight lang="ursa">decl boolean bool</syntaxhighlight>
Boolean values can be set to either true or false, or the result of an expression.
Boolean values can be set to either true or false, or the result of an expression.
<lang ursa>set bool true
<syntaxhighlight lang="ursa">set bool true
# same as
# same as
set bool (= 2 2)
set bool (= 2 2)
</syntaxhighlight>
</lang>
or
or
<lang ursa>set bool false
<syntaxhighlight lang="ursa">set bool false
# same as
# same as
set bool (not (= 2 2))
set bool (not (= 2 2))
</syntaxhighlight>
</lang>

=={{header|VBA}}==
=={{header|VBA}}==
VBA has a boolean type. As an integer False is 0 and anything else is True. However True converts to -1. Booleans are False by default.
VBA has a boolean type. As an integer False is 0 and anything else is True. However True converts to -1. Booleans are False by default.
<lang vb>Dim a As Integer
<syntaxhighlight lang="vb">Dim a As Integer
Dim b As Boolean
Dim b As Boolean
Debug.Print b
Debug.Print b
Line 2,382: Line 2,614:
Debug.Print b
Debug.Print b
a = b
a = b
Debug.Print a</lang>
Debug.Print a</syntaxhighlight>
{{out}}
{{out}}
Output of above lines:<pre>
Output of above lines:<pre>
Line 2,389: Line 2,621:
True
True
-1</pre>
-1</pre>

=={{header|VBScript}}==
=={{header|VBScript}}==
VBScript has the boolean subdatatype and also the two constants <code>True</code> and <code>False</code>.
VBScript has the boolean subdatatype and also the two constants <code>True</code> and <code>False</code>.
When converting an integer to a boolean, <code>0</code> is <code>False</code> and anything not equal to <code>0</code> is <code>True</code>.
When converting an integer to a boolean, <code>0</code> is <code>False</code> and anything not equal to <code>0</code> is <code>True</code>.
<syntaxhighlight lang="vb">
<lang vb>
a = True
a = True
b = False
b = False
Line 2,399: Line 2,630:
x = Int(Rnd * 2) <> 0
x = Int(Rnd * 2) <> 0
y = Int(Rnd * 2) = 0
y = Int(Rnd * 2) = 0
MsgBox a & " " & b & " " & x & " " & y</lang>
MsgBox a & " " & b & " " & x & " " & y</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
True False True False
True False True False
</pre>
</pre>

=={{header|Vim Script}}==
=={{header|Vim Script}}==
A non-zero <code>Number</code> is true, 0 is false.
A non-zero <code>Number</code> is true, 0 is false.


Since a <code>String</code> is converted automatically to a <code>Number</code> when necessary, the following will print "false" because "foo" is converted to 0:
Since a <code>String</code> is converted automatically to a <code>Number</code> when necessary, the following will print "false" because "foo" is converted to 0:
<lang vim>if "foo"
<syntaxhighlight lang="vim">if "foo"
echo "true"
echo "true"
else
else
echo "false"
echo "false"
endif</lang>
endif</syntaxhighlight>
=={{header|V (Vlang)}}==

=={{header|Vlang}}==
V has a ''bool'' type, with literal values for ''true'' and ''false''. Numeric values are not used in conditional statements. 0 is not treated as false, and non-zero does not mean true, in V.
V has a ''bool'' type, with literal values for ''true'' and ''false''. Numeric values are not used in conditional statements. 0 is not treated as false, and non-zero does not mean true, in V.


<lang go>// Boolean Value, in V
<syntaxhighlight lang="go">// Boolean Value, in V
// Tectonics: v run boolean-value.v
// Tectonics: v run boolean-value.v
module main
module main
Line 2,435: Line 2,664:


if 0 == 1 { println("bad result") } else { println(f) }
if 0 == 1 { println("bad result") } else { println(f) }
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,446: Line 2,675:
WDTE has a built-in boolean type, the two values of which are exposed by the <code>std</code> package's <code>true</code> and <code>false</code> functions. In general, however, built-in conditional functionality, such as <code>switch</code> expressions, considers any value that is not <code>true</code> to be <code>false</code>.
WDTE has a built-in boolean type, the two values of which are exposed by the <code>std</code> package's <code>true</code> and <code>false</code> functions. In general, however, built-in conditional functionality, such as <code>switch</code> expressions, considers any value that is not <code>true</code> to be <code>false</code>.


<lang wdte>let io => import 'io';
<syntaxhighlight lang="wdte">let io => import 'io';
let ex => switch 'this is irrelevant for this example' {
let ex => switch 'this is irrelevant for this example' {
false => 'This is, obviously, not returned.';
false => 'This is, obviously, not returned.';
Line 2,452: Line 2,681:
true => 'This is returned.';
true => 'This is returned.';
};
};
ex -- io.writeln io.stdout;</lang>
ex -- io.writeln io.stdout;</syntaxhighlight>


The above prints "This is returned."
The above prints "This is returned."

=={{header|Wren}}==
=={{header|Wren}}==
Wren has a core class, Bool, which has two instances ''true'' and ''false'' which are also ''reserved words'' in the language.
Wren has a core class, Bool, which has two instances ''true'' and ''false'' which are also ''reserved words'' in the language.


This class has two methods: the operator ''!'' which returns the logical complement of its receiver and ''toString'' which returns its string representation.
This class has two methods: the operator ''!'' which returns the logical complement of its receiver and ''toString'' which returns its string representation.
<lang ecmascript>var embed = true
<syntaxhighlight lang="wren">var embed = true
System.printAll([embed, ", ", !embed, ", ", "Is Wren embeddable? " + embed.toString])</lang>
System.printAll([embed, ", ", !embed, ", ", "Is Wren embeddable? " + embed.toString])</syntaxhighlight>


{{out}}
{{out}}
Line 2,470: Line 2,698:
=={{header|XLISP}}==
=={{header|XLISP}}==
Boolean "false" may be represented by <tt>#F</tt>, <tt>#!FALSE</tt>, <tt>NIL</tt>, or the empty list; any other value is counted as true in conditional expressions, but it is also possible to represent the Boolean value "true" using your choice of the symbols <tt>#T</tt>, <tt>#!TRUE</tt>, and <tt>T</tt>. All these symbols are case-insensitive. Note that <tt>T</tt>, unlike the others, is a variable: it is bound by default to the constant <tt>#T</tt>, but you can (although you shouldn't) assign it any other value including "false" (by doing something like <tt>(setq t nil)</tt>). Boolean values are printed as <tt>#T</tt> and <tt>()</tt>.
Boolean "false" may be represented by <tt>#F</tt>, <tt>#!FALSE</tt>, <tt>NIL</tt>, or the empty list; any other value is counted as true in conditional expressions, but it is also possible to represent the Boolean value "true" using your choice of the symbols <tt>#T</tt>, <tt>#!TRUE</tt>, and <tt>T</tt>. All these symbols are case-insensitive. Note that <tt>T</tt>, unlike the others, is a variable: it is bound by default to the constant <tt>#T</tt>, but you can (although you shouldn't) assign it any other value including "false" (by doing something like <tt>(setq t nil)</tt>). Boolean values are printed as <tt>#T</tt> and <tt>()</tt>.

=={{header|XPL0}}==
=={{header|XPL0}}==
An integer value equal to 0 is false, and a value not equal to 0 is true.
An integer value equal to 0 is false, and a value not equal to 0 is true.
Relational operations evaluate to 0 for false and -1 for true. The
Relational operations evaluate to 0 for false and -1 for true. The
command word 'true' equals -1, and 'false' equals 0.
command word 'true' equals -1, and 'false' equals 0.

=={{header|XSLT}}==
=={{header|XSLT}}==
<lang xml><xsl:if test="true() or false()">
<syntaxhighlight lang="xml"><xsl:if test="true() or false()">
True and false are returned by built-in XPath functions.
True and false are returned by built-in XPath functions.
</xsl:if>
</xsl:if>
Line 2,485: Line 2,711:
<xsl:if test="@myAttribute or not($nodeSet)">
<xsl:if test="@myAttribute or not($nodeSet)">
Test an attribute for its presence (empty or not), or whether a node set is empty.
Test an attribute for its presence (empty or not), or whether a node set is empty.
</xsl:if></lang>
</xsl:if></syntaxhighlight>
=={{header|Z80 Assembly}}==
There are no official constants for True or False, however the common convention is to use 0 for false and nonzero for true. In reality, any mutually exclusive condition will work. True/False can be tested using a variety of instructions. The most common are <code>CP</code> and <code>BIT</code> but in certain cases it can be done faster using <code>AND</code> or even <code>RRCA</code>.


All of the following can be used to test if the rightmost bit of a byte is 1.
<syntaxhighlight lang="z80">BIT 0,A
jr nz,true
;;;;;;;;;;;;;;;;
AND 1
jr nz,true
;;;;;;;;;;;;;;;;
RRCA
jr c,true</syntaxhighlight>

Of these three methods, the last one is the fastest and takes the least amount of bytes to encode. However, it does destroy the variable, which may not be an option depending on what you need to do with that data later. <code>BIT</code> is slower than the rest but doesn't alter registers or memory, just the flags, which is sometimes exactly what you need.
=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>a:=True;
<syntaxhighlight lang="zkl">a:=True;
b:=False;
b:=False;
True.dir();</lang>
True.dir();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,502: Line 2,741:
name numObjects oID otype properties size type typeID vaultPath
name numObjects oID otype properties size type typeID vaultPath
</pre>
</pre>

=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang="zonnon">


var
var
Line 2,513: Line 2,751:
c := 1 > 2;
c := 1 > 2;
...
...
</syntaxhighlight>
</lang>
{{omit from|ML/I}}
{{omit from|ML/I}}

Latest revision as of 16:41, 20 February 2024

Task
Boolean values
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Show how to represent the boolean states "true" and "false" in a language.

If other objects represent "true" or "false" in conditionals, note it.


Related tasks



8th

In 8th, any non-zero number is true, as is the specific boolean value 'true'. Everything else evaluates as 'false' (including the boolean value, 'false')

11l

11l defines a built-in data type Bool, which has two values represented by the constants 0B and 1B.

360 Assembly

The are no TRUE or FALSE constants in 360 Assembly; but an often used convention is :

FALSE    DC     X'00'
TRUE     DC     X'FF'

6502 Assembly

There are no built-in true or false constants, but the functionality can be easily replicated with zero or nonzero values (or any two values which can cause a mutually exclusive branch condition, such as with #$7f and #$80 and using BMI/BPL)

8051 Assembly

A single bit represents true or false. By convention, 0 (cleared) is false, 1 (set) is true. In the following, "bit" represents the direct address of any of the 256 directly accessible bits.

clr bit ; clears
setb bit ; sets

68000 Assembly

There are no built-in true or false constants, but the functionality can be easily replicated with zero or nonzero values (or any two values which can cause a mutually exclusive branch condition, such as with #$7f and #$80 and using BMI/BPL)

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program boolean.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ FALSE,  0      // or other value
.equ TRUE,   1      // or other value
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessTrue:    .asciz "The value is true.\n"
szMessFalse:   .asciz "The value is false.\n"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss 
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main 
main:                            // entry of program 
 
    mov x0,0
    //mov x0,#1                  //uncomment pour other test
    cmp x0,TRUE
    bne 1f
                                 // value true
    ldr x0,qAdrszMessTrue
    bl affichageMess
    b 100f
1:   // value False
    ldr x0,qAdrszMessFalse
    bl affichageMess
 
100:                             // standard end of the program */
    mov x0,0                     // return code
    mov x8,EXIT                  // request to exit program
    svc 0                        // perform the system call
qAdrszMessTrue:         .quad szMessTrue
qAdrszMessFalse:        .quad szMessFalse
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

ACL2

Same as Boolean Values#Common Lisp.

Action!

PROC Test(BYTE v)
  PrintF("Variable v has value %B%E",v)
  IF v THEN
    PrintE("Condition IF v is satisfied.")
  ELSE
    PrintE("Condition IF v is not satisfied.")
  FI
  IF v=0 THEN
    PrintE("Condition IF v=0 is satisfied.")
  ELSE
    PrintE("Condition IF v=0 is not satisfied.")
  FI
  IF v<>0 THEN
    PrintE("Condition IF v<>0 is satisfied.")
  ELSE
    PrintE("Condition IF v<>0 is not satisfied.")
  FI
  IF v#0 THEN
    PrintE("Condition IF v#0 is satisfied.")
  ELSE
    PrintE("Condition IF v#0 is not satisfied.")
  FI
  PutE()
RETURN

PROC Main()
  Test(0)
  Test(1)
  Test(86)
RETURN
Output:

Screenshot from Atari 8-bit computer

Variable v has value 0
Condition IF v is not satisfied.
Condition IF v=0 is satisfied.
Condition IF v<>0 is not satisfied.
Condition IF v#0 is not satisfied.

Variable v has value 1
Condition IF v is satisfied.
Condition IF v=0 is not satisfied.
Condition IF v<>0 is satisfied.
Condition IF v#0 is satisfied.

Variable v has value 86
Condition IF v is satisfied.
Condition IF v=0 is not satisfied.
Condition IF v<>0 is satisfied.
Condition IF v#0 is satisfied.

Ada

Ada has a predefined discrete type with the specification:

   type Boolean is (False, True);

with Boolean lattice and relational operations defined on it. See RM A.1.

ALGOL 68

Translation of: python
Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

ALGOL 68 Enforces strong typing and so has few default coercions. The appropriate operators must be used to convert to and from bool[ean] and the following code demonstrates principle conversions:

BOOL f = FALSE, t = TRUE;
[]BOOL ft = (f, t);
STRING or = " or ";
FOR key TO UPB ft DO
  BOOL val = ft[key];
  UNION(VOID, INT) void = (val|666|EMPTY);
  REF STRING ref = (val|HEAP STRING|NIL);
  INT int = ABS val; 
  REAL real = ABS val; 
  COMPL compl = ABS val;
  BITS bits = BIN ABS val; # or bitspack(val); #
  BYTES bytes = bytes pack((val|"?"|null char)*bytes width);
  CHAR char = (val|"?"|null char);
  STRING string = (val|"?"|""); 
 
  print((((val | "TRUE" | "FALSE" ), ": ", val, or, (val|flip|flop), new line)));
  print(("  void: ", " => ", (void|(VOID):FALSE|TRUE), new line));
  print(("   ref: ", " => ", ref ISNT REF STRING(NIL), new line));
  print(("   int: ", int     , " => ", int /= 0, new line));
  print(("  real: ", real    , " => ", real /= 0, new line));
  print((" compl: ", compl   , " => ", compl /= 0, new line));
  print(("  bits: ", bits    , " => ", ABS bits /= 0, or, bits /= 2r0, or, 
                     bits width ELEM bits, or, []BOOL(bits)[bits width], new line));
  print((" bytes: """, STRING(bytes)    , """ => ", 1 ELEM bytes /= null char, or, 
                       STRING(bytes) /= null char*bytes width, or, 
                       STRING(bytes)[1] /= null char, new line));
  print(("  char: """, char  , """ => ", ABS char /= 0 , or, char /= null char, new line));
  print(("string: """, string  , """ => ", string /= "", or, UPB string /= 0, new line));
  print((new line))
OD
Output:
FALSE: F or F
  void:  => F
   ref:  => F
   int:          +0 => F
  real: +0.00000000000000e  +0 => F
 compl: +0.00000000000000e  +0+0.00000000000000e  +0 => F
  bits: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF => F or F or F or F
 bytes: "" => F or F or F
  char: "" => F or F
string: "" => F or F

TRUE: T or T
  void:  => T
   ref:  => T
   int:          +1 => T
  real: +1.00000000000000e  +0 => T
 compl: +1.00000000000000e  +0+0.00000000000000e  +0 => T
  bits: FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFT => T or T or T or T
 bytes: "????????????????????????????????" => T or T or T
  char: "?" => T or T
string: "?" => T or T

Note: The string repr[esentation] of false and true are defined by the variables flop and flip respectively.

ALGOL W

The boolean type is called logical in Algol W - the values are represented by the keywords true and false. Numbers, strings etc. cannot be used where logical values are required.

APL

0 and 1 are used for boolean types in APL (as in J below).

    1 ^ 1
1
    1 ^ 0
0

AppleScript

AppleScript has built-in boolean keywords true and false. Numbers do not work in place of boolean expressions, but they do coerce to and from.

1 > 2     --> false 
not false --> true

{true as integer, false as integer, 1 as boolean, 0 as boolean}
          --> {1, 0, true, false}

true = 1  --> false

AppleScript also has constants yes and no, which coerce easily to boolean values. They have little practical value in AppleScript except if one wishes to use them as arguments in place of boolean values for novelty's sake. They are interchangeable with boolean values as parameters in AppleScriptObjC (not demonstrated here).

{yes as boolean, no as boolean}
          --> {true, false}

yes and no do not coerce to integer values.

Finally, AppleScript also includes keywords with and without, used in declaring parameters for and sending parameters of boolean nature to handlers. They are synonymous with true and false, respectively, and the compiler will sometimes perform the substitution at compile time.

sortItems from L given reversal : true

gets compiled immediately to become:

sortItems from L with reversal

However, the equivalent call to the handler utilising yes, whilst accepted readily in place of its boolean counterpart, is left alone by the compiler:

sortItems from L given reversal:yes

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program areaString.s   */

/* Constantes    */
@ The are no TRUE or FALSE constants in ARM Assembly
.equ FALSE,  0      @ or other value
.equ TRUE,   1      @ or other value
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
/* Initialized data */
.data
szMessTrue: .asciz "The value is true.\n"
szMessFalse: .asciz "The value is false.\n"

/* UnInitialized data */
.bss 

/*  code section */
.text
.global main 
main:                /* entry of program  */
    push {fp,lr}    /* saves 2 registers */
 
    mov r0,#0
    //mov r0,#1   @uncomment pour other test
    cmp r0,#TRUE
    bne 1f
    @ value true
    ldr r0,iAdrszMessTrue
    bl affichageMess
    b 100f
1:   @ value False
    ldr r0,iAdrszMessFalse
    bl affichageMess
 
100:   /* standard end of the program */
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call
iAdrszMessTrue:		.int szMessTrue
iAdrszMessFalse:		.int szMessFalse
/******************************************************************/
/*     display text with size calculation                         */ 
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save  registres */ 
    push {r0,r1,r2,r7}    		/* save others registers */
    mov r2,#0   				/* counter length */
1:      	/* loop length calculation */
    ldrb r1,[r0,r2]  			/* read octet start position + index */
    cmp r1,#0       			/* if 0 its over */
    addne r2,r2,#1   			/* else add 1 in the length */
    bne 1b          			/* and loop */
                                /* so here r2 contains the length of the message */
    mov r1,r0        			/* address message in r1 */
    mov r0,#STDOUT      		/* code to write to the standard output Linux */
    mov r7, #WRITE             /* code call system "write" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7}     		/* restaur others registers */
    pop {fp,lr}    				/* restaur des  2 registres */ 
    bx lr	        			/* return  */

Arturo

a: true
b: false

if? a [ print "yep" ] else [ print "nope" ]

if? b -> print "nope" 
else  -> print "yep"
Output:
yep
yep

AutoHotkey

When an expression is required to evaluate to true or false (such as an IF-statement), a blank or zero result is considered false and all other results are considered true. Operators such as NOT/AND/OR/>/=/< automatically produce a true or false value: they yield 1 for true and 0 for false. A variable can be used to hold a false value simply by making it blank or assigning 0 to it. The words 'true' and 'false' are built-in variables containing 1 and 0. They can be used to make a script more readable.

Avail

While Avail has many methods for handling booleans, boolean itself is simply an enumeration type of the atoms true and false. This enumeration and these atoms are only special by convention of being used for the logical operations provided by the standard library. It would be perfectly possible to define an entirely new boolean system with new types and atoms (or values).

AWK

There is no keyword for true or false in awk. In awk, any nonzero numeric value or any nonempty string value is true. Any other value (zero or the null string "") is false. Values containing only zeros may produce true or false depending on whether they are obtained from the datasource or by assignment, and different results may be obtained according to which version of awk is being used.

In the following example we use zero for false, and one for true to assign boolean values. However, this is just a convention, so other values may also have been used:

BEGIN {
   # Do not put quotes round the numeric values, or the tests will fail
   a = 1    # True
   b = 0    # False

   # Boolean evaluations
   if (a) { print "first test a is true" }        # This should print
   if (b) { print "second test b is true" }       # This should not print
   if (!a) { print "third test a is false" }      # This should not print
   if (!b) { print "forth test b is false" }      # This should print

   # Boolean evaluation using comparison against zero
   if (a == 0) { print "fifth test a is false" }  # This should not print
   if (b == 0) { print "sixth test b is false" }  # This should print
   if (a != 0) { print "seventh test a is true" } # This should print
   if (b != 0) { print "eighth test b is true" }  # This should not print

 }

Axe

In Axe, there are no keywords for true and false. Any expression that evaluates to zero is considered false, and any expression that evaluates to non-zero is considered true. Unlike other languages, there is no canonical value for true (e.g. 1).

BASIC

Most BASICs have no keywords for true and false. Boolean expressions evaluate to 0 when false, and a non-zero value (traditional versions of basic use a value of one, although some variants use a value of negative one) when true. Numbers also work in place of boolean expressions following those rules.

10 LET A%=0
20 LET B%=NOT(A%)
30 PRINT "THIS VERSION OF BASIC USES"
40 PRINT B%; " AS ITS TRUE VALUE"
50 IF A% THEN PRINT "TEST ONE DOES NOT PRINT"
60 IF B% THEN PRINT "TEST TWO DOES PRINT"
70 IF A%=0 THEN PRINT "TEST THREE (FALSE BY COMPARISON) DOES PRINT"
80 IF B%=0 THEN PRINT "TEST FOUR (FALSE BY COMPARISON) DOES NOT PRINT"
90 IF A%<>0 THEN PRINT "TEST FIVE (TRUE BY COMPARISON) DOES NOT PRINT"
100 IF B%<>0 THEN PRINT "TEST SIX (TRUE BY COMPARISON) DOES PRINT"
110 END

Applesoft BASIC

IF statement condition treats any non-zero numeric value as true. Comparison operators evaluate to 1 (true) or 0 (false).

Examples:

? 2 = 3
? 2 = 2
IF 7 THEN ?"HELLO"
Output:
0
1
HELLO

BaCon

' Boolean TRUE and FALSE are non-zero and zero constants
a = TRUE
b = FALSE
PRINT a, ", ", b

IF 0 THEN PRINT "TRUE" : ELSE PRINT "FALSE"
IF 1 THEN PRINT "TRUE"
IF 2 THEN PRINT "TRUE"
Output:
prompt$ bacon boolean.bac
Converting 'boolean.bac'... done, 8 lines were processed in 0.004 seconds.
Compiling 'boolean.bac'... cc  -c boolean.bac.c
cc -o boolean boolean.bac.o -lbacon -lm
Done, program 'boolean' ready.
prompt$ ./boolean
1, 0
FALSE
TRUE
TRUE

BASIC256

' BASIC256 used numbers to represent true and false
' values.  Zero is false and anything else is true.
' The built in constants true and false exist
' and represent one and zero respectively.

print false
print true

BBC BASIC

      REM BBC BASIC uses integers to represent Booleans; the keywords
      REM FALSE and TRUE equate to 0 and -1 (&FFFFFFFF) respectively:
      
      PRINT FALSE
      PRINT TRUE

Cherrycake

The boolean value of true in Cherrycake is represented with a 'true' keyword, and the boolean value of false in Cherrycake is represented with a 'false' keyword. Booleans can also be represented with other types, such as binary and integers. In binary types, 0x01 and 0b01 represent true, and 0x00 and 0b00 represent false. In integer types, 1 represents true and 0 represents false.

Commodore BASIC

Commodore BASIC evaluates any non-zero number for TRUE—but is typically represented as 16-bit signed integer value of -1 or $FFFF—and zero evaluates to FALSE.

10 f%=("z"="a") : t%=not f% : rem capture a boolean evaluation
15 print chr$(147);chr$(14);
20 print "True is evaulated as:";t%
30 print "False is evaluated as:";f%
40 print:print "Any non-zero number will evaluate to"
50 print "true as shown in this example:":print
60 for i=-2 to 2
70 print i;" = ";
80 if i then print "True":goto 100
90 print "False"
100 next
Output:
True is evaulated as:-1                 
False is evaluated as: 0                
                                        
Any non-zero number will evaluate to    
true as shown in this example:          
                                        
-2  = True                              
-1  = True                              
 0  = False                             
 1  = True                              
 2  = True                              
                                        
ready.
█

FreeBASIC

FreeBASIC has a built-in Boolean type (equivalent to a signed one byte integer) with built-in constants true and false to represent values of that type. Note also that:

  • Numeric expresions can be converted to the Boolean type either implicitly or using the CBool operator - zero is converted to false and non-zero to true.
  • Boolean expressions can be converted to a numeric type either implicitly or using the appropriate cast operator (CInt, CByte, CDbl etc) - false is converted to 0 and true to -1.
  • String expressions such as "false" and "true" (regardless of case) can also be converted to Boolean using CBool.
  • It is possible to overload CBool for user-defined types to yield a Boolean value.


Sample code:

' FB 1.05.0 Win64

Dim i As Integer = 23
Dim s As String = "False"
Dim b As Boolean
b = i
Print b
b = CBool(s)
Print b
i = b
Print i
i = CInt(true)
Print i
Sleep
Output:
true
false
 0
-1

Liberty BASIC

IF-statement, loop condition treats any non-zero integer as true. Comparison operators evaluate to 1 (true) or 0 (false).

Microsoft Small Basic

Microsoft Small Basic has two constants: "True" and "False".

If c Then
  notc = "False"
Else
  notc = "True"
EndIf

PowerBASIC

In addition to what's noted above under BASIC, PowerBASIC for Windows and PowerBASIC Console Compiler have the ISTRUE and ISFALSE functions. According to the help file, they "return the logical truth or falsity of a given expression". (PowerBASIC lacks a boolean data type, so the usual practice is to use integers in PB/DOS, and longs in PB/CC and PB/Win.)

DIM x AS LONG
x = ISTRUE(1 = 1)  ' returns -1
x = ISTRUE(1 = 0)  ' returns 0
x = ISFALSE(1 = 1) ' returns 0
x = ISFALSE(1 = 0) ' returns -1

PureBasic

PureBasic does not have a Boolean variable type. An integer type is typically used instead. Boolean values are only supported as part of a loop's condition (While/Wend, Repeat/Until) or in a conditional (If/Endif). In these cases if the result of a variable or a numeric expression is zero it is evaluated as False, otherwise it is evaluated as True. A string variable assigned a null string would be evaluated as False.

QBasic

QBasic, QuickBASIC, VB-DOS and GW-BASIC doesn't have a Boolean type. What it does is to take 0 as False, and any other value as True. The easiest way in QBASIC, QuickBASIC and VB-DOS is to create False and True constants of type Integer and, then, use them as needed:

CONST FALSE=0
CONST TRUE = Not FALSE
Print FALSE
Print TRUE

In GW-BASIC you can create a variable called FALSE% and other called TRUE% and do the same. Nevertheless, is more sure to create functions in order to avoid the value to be manipulated:

10 DEF FNFALSE = 0
20 DEF FNTRUE = NOT FNFALSE
30 Print FNFALSE
40 Print NFTRUE

Run BASIC

Basically 0 is false and 1 is true

if 1          then print "1 is true"
if not(0)     then print "0 is false" 
if 1 < 2      then print "1 < 2 TRUE"
if 2 > 1      then print "2 > 1 TRUE"
if not(2 < 1) then print "2 not < 1"
if not(1 = 0) then print "1 not = 0"

SmallBASIC

a = true
b = false

smart BASIC

  • IF/THEN statements treat any non-zero value as true and zero as false.
  • Comparison operators DO NOT calculate in smart BASIC. For example, PRINT (1 > 4) WILL NOT evaluate to produce a zero value (0) indicating a false condition. It will produce an error. All Boolean evaluations in smart BASIC must be determined within IF/THEN statements.

TI-89 BASIC

There are boolean literals true and false. No other values may be used where a boolean is expected.

True BASIC

!True BASIC maneja correctamente las expresiones booleanas,
!Pero no tiene un tipo booleano. 

!La solución: crear constantes False y True y usarlas según sea necesario."
LET False = 0
LET True =  1
PRINT True; ", "; False

IF True = 0 THEN PRINT "TRUE" ELSE PRINT "FALSE"
IF True > False THEN PRINT "TRUE" ELSE PRINT "FALSE"

!Para el operador NOT, los paréntesis rodean la cláusula completa.
IF Not(2 < 1) then PRINT "TRUE" ELSE PRINT "FALSE"

END
Output:
1 ,  0
FALSE
TRUE
TRUE

uBasic/4tH

In conditionals, zero is false, non-zero is true. Note that = is not only used for assignment, it is also a fully qualified logical operator, so it is easy to assign a true boolean to a variable.

t = 1 = 1
f = 0 = 1

Print "False = ";f;", True = ";t
Output:
False = 0, True = 1

0 OK, 0:52

Yabasic

// Yabasic usa números para representar los valores true y false
// Las constantes incorporadas true y false representan uno y cero respectivamente.

//false también puede escribirse como FALSE o incluso FaLsE.
//true también puede escribirse como TRUE o incluso TrUe.

print false
print true
end

Visual Basic

VB has the Boolean data type and the constants True and False, in addition to what's listed under BASIC, above. When used outside of a boolean context, True and False return values depending on their context -- -1 and 0 in a numeric context, "True" and "False" if used as strings.
When converting an integer to a boolean, 0 is False and anything not equal to 0 is

Dim x As Boolean
x = IIf(Int(Rnd * 2), True, False)
MsgBox x

Batch File

The closest thing to Boolean values in batch files is using if defined. If a variable has any value, it will evaluate to true.

You can make a variable false by clearing its value set "var=".

@echo off

::true
set "a=x"
::false
set "b="

if defined a (
	echo a is true
) else (
	echo a is false
)
if defined b (
	echo b is true
) else (
	echo b is false
)

pause>nul

Output:

a is true
b is false

bc

POSIX bc doesn't define Boolean values (i.e. it's up to the programmer which values represent false and true).

In GNU bc, 0 is false and any other value is true (but the result of a boolean expression will always be 1 if it is true).

Befunge

Zero is false, non-zero is true. This is only used by the horizontal and vertical switch operators (_ and |).

Binary Lambda Calculus

The standard representations for the booleans in lambda calculus are true = \then. \else. then, false = \then. \else. else, which correspond to BLC programs 00 00 110 and 00 00 10.

BQN

For predicates, the boolean value given must be 0 or 1. All other values error.

{1?34}
  34
{⟨⟩?34}
  ERROR

For logical assertion, the test is simply whether the right argument is 1 (𝕩≡1). Anything other than 1 will cause an error.

!1
  1
!⟨⟩
  ERROR
!0
  ERROR

Bracmat

Bracmat operates with success and failure instead of true and false. Success and failure play the same role as true and false in conditional tests, but they are not values like true and false. Instead, success and failure are properties of expressions in addition to values. The simplest failing expression is the atomic expression ~. The simplest succeeding atomic expression is the empty string "" (or ()). A slightly more complex failing expression is 1+1:3, which postulates that 3 matches the result of adding 1 and 1, while 1+1:2 of course succeeds.

Brainf***

Zero is false, non-zero is true. This is only used by the loop brackets ([ and ]).

C

In C, a value which is equal to 0 is false, while a value which is not equal to 0 is true. Relational and logical operators evaluate to 0 for false and 1 for true. Any of the following can be used:

  • any integer type, where 0 gives false, and any other value gives true (note that in C, character types are also integer types, therefore this also applies to characters: the '\0' character is false)
  • any floating point type, where again, 0 gives false and everything else gives true
  • any enumeration type, again 0 gives false, anything else true
  • any pointer type, where the null pointer gives false and any other pointer gives true
  • in C99, the boolean type bool (defined in header <stdbool.h>), where true gives true and false gives false
  • in C99, any complex number type, where 0 (0 real and 0 imaginary) gives false, anything else gives true

C#

In C#, there are the reserved keywords true and false. Variables to hold these values are declared as either bool or Boolean. These types are identical, as bool is just shorthand for Boolean. The collection type BitArray returns its values as Boolean, packing 8 values into each byte (In contrast, the Boolean type uses the entire byte for one value).

There is also the Nullable<T> type that represents all values of its underlying value type T and an additional null value. It has a shorthand notation: T? (When T is a reference type, T? means something else. It is not a different type, but just a hint to the compiler.) So, when applied to bool, we have a bool? type that supports 3 values: true, false and null. This can be useful for some applications where the value can be undefined or missing.

bool? value = null

Unlike C/C++, there is no conversion in C# between other types and Boolean.

C++

In C++, there are the constants true and false to represent those values. However, there are numerous implicit conversions to bool, therefore in conditions (and other contexts expecting boolean values), any of the following can be used:

  • any integer type, where 0 converts to false, and any other value converts to true (note that in C++, character types are also integer types, therefore this also applies to characters: the '\0' character is false)
  • any floating point type, where again, 0 gives false and everything else gives true
  • any enumeration type, again 0 gives false, anything else true
  • any pointer type, where the null pointer gives false and any other pointer gives true
  • any user-defined type with an implicit conversion operator either to bool or to a built-in type which itself can be converted to bool (i.e. any of the above). The C++ standard library contains one such implicit conversion: the implicit conversion of a stream s to bool gives !s.fail()

Clean

The standard library defines a data type Bool, which has exactly two members:

::Bool = False | True

In addition to all the functionality of any other Clean algebraic data type (e.g. pattern matching), and the specified derived typeclass instances, the built-in guard (“|”) and if syntaxes use Bool.

As with any other Clean data type, there are no automatic conversions of other types to Bool.

Clojure

The boolean constants are true and false. In a conditional context, the only false values are false and nil -- every other value is true.

CMake

foreach(var 1 42 ON yes True y Princess
            0 OFF no False n Princess-NOTFOUND)
  if(var)
    message(STATUS "${var} is true.")
  else()
    message(STATUS "${var} is false.")
  endif()
endforeach(var)
-- 1 is true.
-- 42 is true.
-- ON is true.
-- yes is true.
-- True is true.
-- y is true.
-- Princess is true.
-- 0 is false.
-- OFF is false.
-- no is false.
-- False is false.
-- n is false.
-- Princess-NOTFOUND is false.

The strings "0", "OFF", "NO", "FALSE" and "N" (ignoring case) are false. Any string ending with "-NOTFOUND" (ignoring case) is false. All other strings are true.

Scripts that want if(TRUE) should require CMake 2.8; do refer to cmake --help-policy CMP0012.

COBOL

Booleans

Booleans are defined as any data item having a PICTURE made up of ones.

       01  some-bool               PIC 1 BIT.

The boolean literals B"1" and B"0" represent true and false, respectively.

Conditions

Prior to COBOL 2002, there was no boolean data type, only condition names which could be used in conditional expressions. Condition names are subordinate to another data item, have the level-number 88, and are defined with the value(s) which their parent data item must have for them to be set to true. They can be defined like so:

       01  X PIC 9.
           88 X-Is-One        VALUE 1.
           88 X-Is-Even       VALUE 0 2 4 6 8.
           88 X-Larger-Than-5 VALUE 6 THRU 9.

Conditions can be SET to TRUE or FALSE. Setting a condition to TRUE will move the (first) value in the VALUE clause to the parent data item. In COBOL 2002, an optional FALSE clause was added which allowed the condition to be SET to FALSE and consequently set the parent data item to the specified value in the clause. A FALSE clause can only have one value. An example of conditions in action:

       PROGRAM-ID. Condition-Example.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  Foo PIC 9 VALUE 5.
           88  Is-Not-Zero VALUE 1 THRU 9
               WHEN SET TO FALSE IS 0.

       PROCEDURE DIVISION.
       Main.
           PERFORM Is-Foo-Zero

           SET Is-Not-Zero TO FALSE
           PERFORM Is-Foo-Zero

           SET Is-Not-Zero TO TRUE
           PERFORM Is-Foo-Zero

           GOBACK
           .

       Is-Foo-Zero.
           IF Is-Not-Zero
               DISPLAY "Foo is not zero, it is " Foo "."
           ELSE
               DISPLAY "Foo is zero."
           END-IF
           .
Output:
Foo is not zero, it is 5.
Foo is zero.
Foo is not zero, it is 1.

CoffeeScript

CoffeeScript is largely based on JavaScript, but that may only serve to confuse you. Your best bet is to learn all the cases:

h1 = {foo: "bar"}
h2 = {foo: "bar"}

true_expressions = [
  true
  1
  h1? # because h1 is defined above
  not false
  !false
  []
  {}
  1 + 1 == 2
  1 == 1 # simple value equality
  true or false
]

false_expressions = [
  false
  not true
  undeclared_variable?
  0
  ''
  null
  undefined
  h1 == h2 # despite having same key/values
  1 == "1" # different types
  false and true
]

Common Lisp

The only value in Common Lisp that is false is the symbol nil; all other values are true. The symbol t is the canonical true value.

Considered as variables, nil and t are bound to themselves ("self-evaluating"). nil, as well as being false, is used as the empty list; i.e. an empty list is false.

For more information, follow the links from CLHS: Type BOOLEAN.

Component Pascal

VAR
   b,c: BOOLEAN;
...
   b := TRUE;
   c := FALSE;
...

Crystal

Crystal uses the "truthiness" of a value to determine whether or not to execute the body of an if, unless, while, or until block.

As mentioned in the language reference, the values nil and false, as well as null pointers are "falsey", all other values are truthy

if false
  puts "false"
elsif nil
  puts "nil"
elsif Pointer(Nil).new 0
  puts "null pointer"
elsif true && "any other value"
  puts "finally true!"
end

D

In D, there are constants false and true to represent their respective values (that also implicitly convert to 0 and 1). Implicit conversions to boolean are listed below:

  • Any integer type, where 0 converts to false, and any other value converts to true;
  • Any floating point type, where again, 0 gives false and everything else (but NaNs) gives true;
  • Any enumeration type, again 0 gives false, anything else true;
  • Any pointer type, where the null pointer gives false and any other pointer gives true;
  • Any class reference type, using the "is" operator, the null reference gives false and any other reference gives true;
  • Any user-defined type with an implicit conversion operator (opCast) either to bool or to a built-in type which itself can be converted to bool.

Dc

In dc there are no built in boolean values or functions. Adopting the way C codes them appears to be a good idea: 0=FALSE and 1=TRUE.

Delphi

In addition to the types defined by Object Pascal, Delphi defines the type Bool.

DWScript

The standard Boolean type has two values: True and False, with Ord(False) = 0 and Ord(True) = 1.

Dyalect

Dyalect has a standard Bool type with two values: true and false. Other types in Dyalect support implicit conversion to booleans. All values except false and nil are converted to true.

Dylan

#t // <boolean> true
#f // <boolean> false

For the purpose of conditional statements, all objects other than #f evaluate to true.

Déjà Vu

Déjà Vu has true and false, two numbers that are equal to 1 and 0 respectively. Every object has a truth value. The only falsy things are numbers equal to zero, empty lists and dictionaries, and zero-length strings and blobs.

E

E defines two basic objects true and false, and the boolean guard which accepts them. All builtin operations which take booleans (e.g. the if control structure) coerce the input to boolean.

? if (true) { "a" } else { "b" }
# value: "a"

? if (false) { "a" } else { "b" }
# value: "b"

? if (90) { "a" } else { "b" }
# problem: the int 90 doesn't coerce to a boolean

No objects in the standard library coerce to boolean, but user-written objects may choose to do so; they can then be used in place of booleans.

? def bowlian {
>     to __conformTo(guard) {
>         if (guard == boolean) { return true }
>     }
> }
> if (bowlian) { "a" } else { "b" }
# value: "a"

EasyLang

EasyLang does not have built-in boolean types or constants. Operators that "return" a boolean type (e.g. >, <=) cannot be used outside of conditional statements and loops.

You can use 1 or 0 in place of true and false.

boolNumber = 1
if boolNumber = 1
   print "True"
else
   print "False"
.

EchoLisp

"All that which is not false is true" - Attribué à L. Wittgenstein - The only false value is the boolean #f. All other objects, including the empty list or null or 0 ..- evaluate to #t = true.

(not #t)   #f
(not #f)   #t
(not null)  #f
(not 0)  #f

Ecstasy

Ecstasy's defines an enumeration named Boolean, which contains the values  False  and  True .

module GeorgeBoole {
    @Inject Console console;

    void run() {
        Boolean f = False;
        assert !f == True;

        // methods like "and", "or", "xor", and "not" are the same as
        // the operators "&"/"&&", "|"/"||", "^"/"^^", and the unary "~"
        assert True.and(False) == True & False == False;
        assert True.or(False)  == True | False == True;
        assert True.xor(False) == True ^ False == True;
        assert True.not() == ~True == False;

        console.print($"0==1 = {0==1}");
        console.print($"!False = {!False}");
    }
}
Output:
0==1 = False
!False = True

EGL

In EGL boolean is a primitive type, however it acts the same as an integer (type int). A boolean and an int accept integer values aswel as true and false keywords (which represent resp. 1 and 0). A boolean is always true except when it has value 0 (or keyword false). A boolean can be converted to a string ("true" or "false") using StrLib.booleanAsString(boolean);

myBool boolean = 0;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = 1;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = 2;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = false;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myBool = true;
SysLib.writeStdout("myBool: " + StrLib.booleanAsString(myBool));
myInt int = 0;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = 1;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = 2;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = false;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
myInt = true;
SysLib.writeStdout("myInt: " + StrLib.booleanAsString(myInt));
Output:
myBool: false
myBool: true
myBool: true
myBool: false
myBool: true
myInt: false
myInt: true
myInt: true
myInt: false
myInt: true

Elena

ELENA uses the system'BaseBoolValue class, which has two singleton sub-classes: system'true and system'false. E.g. an expression like 5 == 5 returns system'true. There is a Boolean variable : system'Boolean.

Elixir

Elixir utilizes Erlang's definition of boolean types; they're defined as the atoms :true and :false. No other type is equal to true or false.

iex(1)> true === :true
true
iex(2)> false === :false
true
iex(3)> true === 1
false

nil (also defined as an atom, :nil) is not equal to false.

iex(4)> nil === :nil
true
iex(5)> nil === false
false

Elm

--True and False directly represent Boolean values in Elm
--For eg to show yes for true and no for false
if True then "yes" else "no"

--Same expression differently
if False then "no" else "yes"

--This you can run as a program
--Elm allows you to take anything you want for representation
--In the program we take T for true F for false
import Html exposing(text,div,Html)
import Html.Attributes exposing(style)

type Expr = T | F | And Expr Expr | Or Expr Expr | Not Expr

evaluate : Expr->Bool
evaluate expression =
 case expression of
 T ->
  True

 F ->
  False

 And expr1 expr2 ->
  evaluate expr1 && evaluate expr2

 Or expr1 expr2 ->
  evaluate expr1 || evaluate expr2

 Not expr ->
  not (evaluate expr)

--CHECKING RANDOM LOGICAL EXPRESSIONS
ex1= Not F
ex2= And T F
ex3= And (Not(Or T F)) T

main =
    div [] (List.map display  [ex1, ex2, ex3])

display expr=
   div [] [ text ( toString expr ++ "-->" ++ toString(evaluate expr) ) ]
--END

Emacs Lisp

Symbol nil is false and symbol t is true. Both are self-evaluating, being variables whose value is their own symbol. See the elisp manual for more.

In an if and similar, nil is false and anything else is true. To make that clear docstrings etc say "non-nil" for true. (See last item in elisp manual documentation tips.)

EMal

^|EMal has a dedicated Logical type expressed by the logic keyword.
 |It's not nullable and holds the two values false and true.
 |There are no implicit conversions, but explicit conversions 
 |from/to int (0,1) or text ("⊥", "⊤") are allowed.
 |^
logic booleanTrue = true
logic booleanFalse = false
if 2 > 1 and true and not false
  writeLine("true: " + true + ", false: " + false)
end
if false == logic!0
  writeLine("explicit conversion from integer")
end
if true == logic!"⊤"
  writeLine("explicit conversion from text")
end
writeLine(int!true) # is one
writeLine(text!false) # is "⊥"
Output:
true: ⊤, false: ⊥
explicit conversion from integer
explicit conversion from text
1
⊥

Erlang

Erlang doesn't technically define boolean types. Instead, the atoms true and false are used. However, they are integrated well enough into the language there should be no problem with that as long as you don't expect false and true to mean anything but literal false and true.

1> 1 < 2.
true
2> 1 < 1.
false
3> 0 == false.
false

Excel

The Logical category of functions includes the constants TRUE() and FALSE() which are displayed without the parantheses in cells. There are logical functions such as AND and OR too. For an AND truth table of two variables, take 3 cells, say A1,B1 and C1. In C1 type in :

=AND(A1;B1)

Copy this until C4. Now as values are filled in from A1-A4 and B1-B4, C1-C4 gets updated.

0	0	FALSE
0	1	FALSE
1	0	FALSE
1	1	TRUE

F#

The type bool is an abbreviation for the .NET framework type System.Boolean.

type bool = System.Boolean

Instances of this type have values of either true or false.

Factor

In Factor any value except f is true, with t being the canonical true value.

FALSE

Zero is false and non-zero is true. This is used by the if and while operators (? and #). Comparators (= and <) yield -1 for true and 0 for false.

Fantom

Conditional statements must return a sys::Bool, and the only two values are true and false.

Forth

In conditionals, zero is false, non-zero is true. There are predefined constants for the canonical forms. For FORTH-83 or later, FALSE is zero and TRUE is -1 (all bits set). For earlier FORTH standards, FALSE is zero and TRUE is 1.

TRUE .    \ -1
FALSE .   \ 0

Fortran

Fortran started off in 1957 with only floating-point and fixed-point variables, so any calculations in the style of Boolean arithmetic would be done with integer values such as zero and not-zero, using multiplication and addition for and and or.

Fortran 66 introduced a logical data type which can be set to either .true. or .false. or be generated via logical expressions such as <=, etc. Such variables cannot be used in normal arithmetic with operators such as +-*/ but only with logical operators such as .OR. and so on. If via the EQUIVALENCE statement their numerical values (or, bit patterns) are inspected as say an integer, the values may well not be as anticipated and differ between computers and compilers. For instance, on the Burroughs 6700 an integer variable equivalenced to a logical variable would appear as .true. if odd, .false. if even.

The default storage size of a LOGICAL variable is the same as the default storage size of an INTEGER variable, which for many systems is 32 bits. This is done to simplify calculations of record sizes, or the alignment of variables in COMMON storage areas. It is usually possible to declare variables with certain byte sizes (normally only powers of two) so that LOGICAL*1 or similar declarations may be available. If used however there may arise alignment issues with adjacent variables of other types (such as REAL) that may require padding to even word boundaries for best access. Consider

      TYPE MIXED
       LOGICAL*1 LIVE
       REAL*8    VALUE
      END TYPE MIXED
      TYPE(MIXED) STUFF(100)

The array STUFF might occupy 900 bytes, or, 1600 bytes if each double-precision value has to be aligned to an eight-byte boundary. In the latter case, it may be better to declare LIVE and VALUE to be separate hundred-element arrays as in

      TYPE MIXED
       LOGICAL*1 LIVE(100)
       REAL*8    VALUE(100)
      END TYPE MIXED
      TYPE(MIXED) STUFF

Except that now only hundred-element variables of type MIXED can be declared. Either way, the record size needed for a disc file holding such items will need careful thought.

Free Pascal

In addition to the types defined by Object Pascal, free Pascal defines the qWordBool, that has a sizeOf eight.
Furthermore, True and False are not keywords from FPC v3.0.0. It is possible to assign any value to true and false, like strings but even objects.

{$mode objfpc}{$ifdef mswindows}{$apptype console}{$endif}
const
  true = 'true';
  false = 'false';
begin
  writeln(true);
  writeln(false);
end.

[ EDIT ]

See https://wiki.freepascal.org/Boolean

While you can assign values to true and false, it has now nothing to do with the boolean values....
Try with this function:

FUNCTION IsNatural ( CONST num: VARIANT ): BOOLEAN;

    BEGIN

	IsNatural := ( num > 0 );

    END;

JPD 2022/08/02

Frink

The literal boolean values are called true and false. In addition, in conditional expressions, the following are treated as true:

  • Any non-empty string
  • Any list, even an empty list

The following are treated as false:

  • The empty string
  • The special value undef

Futhark

Futhark has a bool type, with the two values True and False. They are used for branching.


FutureBasic

FB recognizes two types for boolean truth values: BOOL and boolean. There is a subtle difference between the two. A BOOL will accept without complaint the macros YES, and NO, the equivalent native FB constants, _true, and _false, and, of course, 0 and 1. However, although a BOOL can be assigned other values, it will throw a clang (FB"s native compiler) warning as with this example:

window 1
BOOL boolTest
boolTest = -1
print boolTest
HandleEvents

When compiled this code generates this warning:

implicit conversion from constant value -1 to 'BOOL'; the only well defined values for 'BOOL' are YES and NO [-Wobjc-bool-constant-conversion]

On the other hand, a Boolean can be assigned not only YES, NO, _true, or _false, and 0 or 1, but also other values, such as the common -1, and compile without complaint.

Since FB can also work with objects, native BOOLs and booleans need to be converted to objects as demonstrated in the code below.

Trivia: Because NULL and _nil zero values in FB, they evaluate to "NO" or “_false” in conditional expressions.

void local fn BooleanExercise
  BOOL areEqual    = (1 == 1)      // areEqual is YES
  BOOL areNotEqual = not areEqual  /* areNotEqual is converted to: areEqual = (-(1 == 1)). -1 throws a clang warning.
  NOTE: FB does not accept the "!" shorthand for "not", i.e. !areEqual, common in other languages. */
  
  print "areEqual    == "; areEqual
  print "areNotEqual == "; areNotEqual
  print
  
  // Boolean types assigned values outside YES or NO compile without complaint.
  boolean minusOneTest = -1
  print "minusOneTest == "; minusOneTest
  
  // Typical boolean value is use
  BOOL flatterRosettaReader = YES
  if (flatterRosettaReader)
    print
    print @"Rosetta Code programmers understand booleans."
    print
  end if
  
  // Defined Core Foundation boolean values
  print "kCFBooleanTrue  == "; kCFBooleanTrue
  print "kCFBooleanFalse == "; kCFBooleanFalse
  print
  
  // Number object assigned literal value
  CFNumberRef booleanObject = @(YES)
  print "booleanObject == "; booleanObject
  print
  
  // Number object created programmatically
  booleanObject = NO
  print "booleanObject variable reassigned as N0 == "; fn NumberWithBool( booleanObject )
  print
end fn

window 1

fn BooleanExercise

HandleEvents
Output:
areEqual    == 1
areNotEqual == 0

minusOneTest == -1

Rosetta Code programmers understand booleans.

kCFBooleanTrue  == 1
kCFBooleanFalse == 0

booleanObject == 1

booleanObject variable reassigned as N0 == 0

Gambas

Click this link to run this code

Public Sub Main()
Dim bX As Boolean

Print bX
bX = True
Print bX

End

Output:

False
True

GAP

1 < 2;
# true 

2 < 1;
# false

# GAP has also the value fail, which cannot be used as a boolean but may be used i$

1 = fail;
# false

fail = fail;
# true

Go

Go defines a built-in data type bool, which has exactly two values, represented by the keywords true and false. There is no conversion between booleans and other data types. Conditionals require a boolean value, so if i is a numeric type, for example, you must spell out if i != 0 { if you wish to interpret it as boolean.

The template package however, uses a different rule for if actions. There, it is testing if a "pipeline" is "empty" where the empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.

 
package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {
	var n bool = true
	fmt.Println(n)        // prt true
	fmt.Printf("%T\n", n) // prt bool
	n = !n
	fmt.Println(n) // prt false

	x := 5
	y := 8
	fmt.Println("x == y:", x == y) // prt x == y: false
	fmt.Println("x < y:", x < y)   // prt x < y: true

	fmt.Println("\nConvert String into Boolean Data type\n")
	str1 := "japan"
	fmt.Println("Before :", reflect.TypeOf(str1)) // prt Before : string
	bolStr, _ := strconv.ParseBool(str1)
	fmt.Println("After :", reflect.TypeOf(bolStr)) // prt After : bool
}

Groovy

Groovy has a boolean "primitive" type and a Boolean "object wrapper" type directly derived from Java. See the Java solution to this task for more details.

Unlike Java, any null reference converts to a boolean "false", while any non-null object reference converts to a boolean "true"... EXCEPT if that object has a specific defined conversion to boolean "false". For example, for any numeric type, any zero value representation converts to "false" and any non-zero value converts to "true". For any collection type, non-empty converts to "true" and empty converts to "false".

Haskell

The Haskell standard Prelude defines a data type Bool, which has exactly two members:

data Bool = False | True    deriving (Eq, Ord, Enum, Read, Show, Bounded)

In addition to all the functionality of any other Haskell algebraic data type (e.g. pattern matching), and the specified derived typeclass instances (e.g. False == False, succ False == True, (maxBound :: Bool) == True, etc.), the built-in guard (“|”) and if syntaxes use Bool.

As with any other Haskell data type, there are no automatic conversions of other types to Bool.

HicEst

Zero is false, non-zero is true. Numbers also work in place of boolean expressions following this rule.

HolyC

In HolyC, there are the reserved keywords `TRUE` and `FALSE`. Variables to hold these values are declared as `Bool`.

Any value which is equal to 0 is false, while a value which is not equal to 0 is true. Relational and logical operators evaluate to 0 for false and 1 for true. Any of the following can be used:

  • Any integer type, where 0 gives false, and any other value gives true.
  • Any floating point type, where again, 0 gives false and everything else gives true.
  • Any pointer type, where the null pointer gives false and any other pointer gives true.

i

Any non-zero number is true in 'i'.

main
	//Bits aka Booleans.
	b $= bit()

	b $= true
	print(b)

	b $= false
	print(b)
	
	//Non-zero values are true.
	b $= bit(1)
	print(b)

	b $= -1
	print(b)

	//Zero values are false
	b $= 0
	print(b)
}

Icon and Unicon

Icon and Unicon do not use Boolean values for flow control. Rather they use success (returning a result, any result even a null) or failure (a signal) for this purpose. Built-in controls support not, and (&), and or (|). For an example of how this works, see Short Circuit Evaluation. Icon and Unicon do support bit operations on integers which could be used to record Boolean state. See also Logical Operations for an example of how and when Boolean values might be implemented.

Idris

Idris> :doc Bool
Data type Prelude.Bool.Bool : Type
    Boolean Data Type

Constructors:
    False : Bool


    True : Bool

Inform 6

Inform 6 has the constants true and false, which are identical to 1 and 0 respectively. One of these values will always be yielded by a condition operator (an operator that yields a boolean value). In addition, any non-zero value is considered to be true.

Inform 7

The Boolean type is called "truth state" and has the values "true" and "false".

However, Inform 7 distinguishes between Boolean values and conditions. Comparison expressions do not return truth states, and truth state expressions cannot be used directly in conditional statements. There is a conversion from condition to truth state:

let B be whether or not 123 is greater than 100;

And truth states can be used in conditions by adding an explicit comparison:

if B is true, say "123 is greater than 100."

Phrases (functions) cannot be defined to return a truth state directly. Instead, they are defined using "to decide whether" (or "to decide if") and can then be used as conditions:

To decide whether the CPU is working correctly:
	if 123 is greater than 100, decide yes;
	otherwise decide no.

When play begins:
	[convert to truth state...]
	let B be whether or not the CPU is working correctly;
	[...or use as a condition]
	if the CPU is working correctly, say "Whew."

Insitux

Simply true and false, however, anything which is not false or null is considered truthy.

J

False is 0, true is 1. This is an advantage (search for Maple).

This approach also works well with Bayes' theorem, as false matches 0% probability and true matches 100% probability.

Java

In Java, true and false are used to reference a boolean value.
There is no use of 0 and 1, or undefined vs. defined.

As with the other primitive data-types, boolean has a wrapper class, Boolean, which includes a set of valuable boolean operations.

boolean valueA = true;
boolean valueB = false;

Or.

Boolean valueA = Boolean.TRUE;
Boolean valueB = Boolean.FALSE;

Additionally.

Boolean valueA = Boolean.valueOf(true);
Boolean valueB = Boolean.valueOf(false);

JavaScript

The Boolean type has two values: true and false

The following table shows the result of type conversions to boolean:

  • Undefined: any undefined value is converted to false
  • Null: false
  • Number: the numbers 0, -0, NaN are false; otherwise true
  • String: the empty (zero-length) string is false; otherwise true
  • Object: any object is converted to true

(source: ECMAScript Language Reference)

Joy

The truth literals are true and false. In a conditional context, false, numerical values (including characters) of zero, empty lists and empty sets are evaluated as false.

jq

true and false are the only entities of type "boolean":

$ jq type
true
"boolean"
false
"boolean"

The above shows the jq command invocation, followed by alternating lines of input and output.

jq's logical operators, however, do not require boolean inputs. In brief, false and null are both regarded as false, and all other JSON entities are regarded as true. That is, all values except for false and null are truthy.

Julia

Julia has a built-in Bool type with values true and false.

Other objects do not represent boolean values and cannot be used in conditional expressions, for example:

julia> if 1
         println("true")
       end
ERROR: type: non-boolean (Int64) used in boolean context

However, integers can be converted to boolean types with the bool() function (which treats nonzero values as true)

julia> bool(-2:2)
5-element Bool Array:
  true
  true
 false
  true
  true

KonsolScript

The Boolean type has two values: true and false

The following table shows the result of type conversions to boolean:

  • Number: the number 0 is false; otherwise true
  • String: the empty (zero-length) string is false; otherwise true

`

Kotlin

Booleans in Kotlin are given by the literals true and false, case sensitive, which are the only instances of the class Boolean.

LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.

Lambdatalk

Predefined constants are true and false:

{if true then YES else NO}
-> YES
{if false then YES else NO}
-> NO

Following the lambda calculus user defined booleans can be built

{def TRUE {lambda {:a :b} :a}} 
-> TRUE
{def FALSE {lambda {:a :b} :b}}
-> FALSE
{def IF {lambda {:c :a :b}  {:c :a :b}}}
-> IF

{IF TRUE yes no}
-> yes
{IF FALSE yes no}
-> no

Lasso

Comparisons are evaluated in Lasso as either true of false, so "1 == 2" will evaluate as true, and "1 == 1" will evaluate as true.

A variable can also be assigned a boolean type, and as such then holds either true of false states.

!true
// => false

not false
// => true

var(x = true)
$x // => true

$x = false
$x // => false

In a conditional, if the result is the integer 0, it is also evaluated as boolean false. If the conditional results in an integer greater than zero, it is evaluated as boolean true.

local(x = string)
// size is 0
#x->size ? 'yes' | 'no'

local(x = '123fsfsd')
// size is 8
#x->size ? 'yes' | 'no'
Output:
no
yes

Latitude

In Latitude, an object's truthiness is determined by its toBool method, which must return one of the constants True or False. Obviously, these two constants have trivial toBool methods which return themselves. Nil is also falsy, while most other built-in objects (including numbers, strings, arrays, etc.), including "empty" objects such as the empty string, are truthy.

By convention, objects which are used to represent failure are considered falsy. For instance, the standard library 'unit-test module provides the FailedTest object, which is returned when a unit test fails. This object (and its children) test falsy when used as a conditional.

LFE

> 'true
true
> 'false
false
> (or 'false 'false)
false
> (or 'false 'true)
true

Lingo

Lingo has the constants TRUE and FALSE. In numerical context they have the values 1 and 0. In boolean context any nonzero integer evaluates to TRUE.

put TRUE
-- 1
put FALSE
-- 0
if 23 then put "Hello"
-- "Hello"

Little

For conditionals, numeric variables (including poly variables with a number in them), evaluate to true or false based on their value.

Use the defined() buildin to test if a variable is defined.

For the rest of variable types the value depend if the variable is defined or not.


int a = 0;
int b = 1;
int c;
string str1 = "initialized string";
string str2; //  "uninitialized string";

if (a) {puts("first test a is false");}         // This should not print
if (b) {puts("second test b is true");}         // This should print
if (c) {puts("third test b is false");}         // This should not print
if (!defined(c)) {puts("fourth test is true");} // This should print
if (str1) {puts("fifth test str1 is true");}    // This should print
if (str2) {puts("sixth test str2 is false");}   // This should not print

LiveCode

true and the string "true" are both logical true, similarly for false and "false" being logical false.

Logo has predefined symbols for true and false ("true and "false), which are the values returned by predicates and required by logical operators and conditionals.

print 1 < 0    ; false
print 1 > 0    ; true
if "true [print "yes]    ; yes
if not "false [print "no]  ; no

Unlike other lispy languages, there are no other implicit conversions. You must test explicitly for zero or empty collections.

if equal? 0 ln 1 [print "zero]
if empty? [] [print "empty]    ; empty list
if empty? "|| [print "empty]   ; empty word

Lua

All values in Lua other than false or nil are considered true:

if 0 then print "0" end             -- This prints
if "" then print"empty string" end  -- This prints
if {} then print"empty table" end   -- This prints
if nil then print"this won't print" end
if true then print"true" end
if false then print"false" end      -- This does not print

M2000 Interpreter

True is -1 and False is 0 (double type), but any comparison return boolean. We can define boolean type variables.

Using Switches "+sbl" in console or Set Switches "+sbl" in code in a module, we get Prints of boolean values as True/False or Αληθές/Ψευδές

use Greek to change to 1032 locale and Greek error messages and dialogs

use Latin to change to 1033 locale and English error messages and dialogs

We can use Locale 1032 to change only locale to Greek.

M2000 print in console any character from Unicode, and diacritics (one or more, without moving the cursor).


Module CheckBoolean {
      A=True
      Print Type$(A)="Double"
      B=1=1
      Print Type$(B)="Boolean"
      Print A=B  ' true
      Print A, B   ' -1   True
      Def boolean C=True, D=False
      Print C, D , 1>-3 ' True False True
      K$=Str$(C)
      Print K$="True"  ' True
      Function ShowBoolean$(&x) {
           x=false
           Try {
                        if keypress(32) then x=true : exit
                        If Keypress(13) then exit
                        loop
            }
            =str$(x, locale)
      }
      Wait 100
      Print "C (space for true, enter for false)="; : Print ShowBoolean$(&c)
      Print C
}
CheckBoolean

Print str$(True, "\t\r\u\e;\t\r\u\e;\f\a\l\s\e")="true"
Print str$(False, "\t\r\u\e;\t\r\u\e;\f\a\l\s\e")="false"
Print str$(2, "\t\r\u\e;\t\r\u\e;\f\a\l\s\e")="true"

Maple

The keywords "true" and "false" are the default boolean values. Expressions involving relational operators are evaluated logically using the evalb command. Expressions under assumptions may be evaluated logically using the is command. Types may be tested, resulting in boolean values, using the type command.

Mathematica/Wolfram Language

True and False are the default boolean values. To make any expression a boolean use the Boole[] function.

MATLAB

The keywords "true" and "false" are the default boolean values. But, many functions prefer to return boolean "1" or "0" instead of "true" or "false". It is very important to note that having a function return a numerical 1 or 0 is not the same as a boolean "1" or "0". To make a number or array of numbers a boolean use the logical() function. logical() will convert any non-zero number to a boolean "1" and any zero entries a boolean "0".

Sample Usage: (islogical() is a function that returns a boolean "1" if the input is a boolean, "0" otherwise)

>> islogical(true)

ans =

     1

>> islogical(false)

ans =

     1

>> islogical(logical(1))

ans =

     1

>> islogical(logical(0))

ans =

     1

>> islogical(1)

ans =

     0

>> islogical(0)

ans =

     0

Maxima

is(1 < 2);
/* true */

is(2 < 1);
/* false */

not true;
/* false */

not false;
/* true */

Metafont

Metafont has the type boolean; a boolean variable can be true or false. Using non boolean values (or expressions that do not evaluate to a boolean value) results in a recoverable error; by default, any non-boolean value is interpreted as false.

min

Works with: min version 0.19.3

true and false are the only boolean values in min. The bool function converts various objects to boolean values:

  • non-zero number: true
  • zero number: false
  • non-empty quotation: true
  • empty quotation: false
  • non-empty string: true
  • empty string: false
  • boolean: no conversion performed

MiniScript

In MiniScript, numbers represent boolean values, with additional fuzzy logic for degrees of truth. Built-in constants `true` and `false` are simply aliases for 1 and 0, respectively.

boolTrue = true
boolFalse = false

if boolTrue then print "boolTrue is true, and its value is: " + boolTrue

if not boolFalse then print "boolFalse is not true, and its value is: " + boolFalse

mostlyTrue = 0.8
kindaTrue = 0.4
print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue)
print "mostlyTrue OR kindaTrue: " + (mostlyTrue or kindaTrue)
Output:
boolTrue is true, and its value is: 1
boolFalse is not true, and its value is: 0
mostlyTrue AND kindaTrue: 0.32
mostlyTrue OR kindaTrue: 0.88

Mirah

import java.util.ArrayList
import java.util.HashMap

# booleans 
puts 'true is true' if true
puts 'false is false' if (!false)

# lists treated as booleans
x = ArrayList.new
puts "empty array is true" if x
x.add("an element")
puts "full array is true" if x
puts "isEmpty() is false" if !x.isEmpty()

# maps treated as booleans
map = HashMap.new
puts "empty map is true" if map
map.put('a', '1')
puts "full map is true" if map
puts "size() is 0 is false" if !(map.size() == 0)

# these things do not compile
# value = nil   # ==> cannot assign nil to Boolean value
# puts 'nil is false' if false == nil  # ==> cannot compare boolean to nil
# puts '0 is false' if (0 == false)    # ==> cannot compare int to false

#puts 'TRUE is true' if TRUE   # ==> TRUE does not exist
#puts 'FALSE is false' if !FALSE   # ==> FALSE does not exist

Modula-2

MODULE boo;

IMPORT  InOut;

VAR     result, done            : BOOLEAN;
        A, B                    : INTEGER;

BEGIN
   result := (1 = 2);
   result := NOT result;
   done := FALSE;
   REPEAT
     InOut.ReadInt (A);
     InOut.ReadInt (B);
     done := A > B
   UNTIL done
END boo.

Modula-3

Similar to Ada, Modula-3 has a built-in BOOLEAN type defined as

TYPE BOOLEAN = {FALSE, TRUE}

Monte

Much like E, Monte has built-in objects true and false, and a boolean guard.

def example(input :boolean):
    if input:
        return "Input was true!"
    return "Input was false."

MUMPS

M[UMPS] has no data types per se, however, any value can be coerced to a specific interpretation by applying certain operators.

Internally, the language treats any "zero" value as a "false", and any "non-zero" value as a "true".
Values like 1, 2, 13245.08763, .1, "0.00001234ABC" and "1234ABC" are "true".
Values like 0, -3, "", " 123" (note the leading space in this one), "+++++567", "abc", "abc1245" are "false".

When a boolean operator is applied to an operand, the value of that operand is coerced to a logical value, that is: if the value starts out with a sequence of digits that look like a non-zero number, the value is "true" (1), and otherwise that value is "false" (0).

There are two standardized binary boolean operators: & (and) and ! (or). Newer implementations of the language may also support !! (exclusve or). There is one unary boolean operator: ' (not).

Nanoquery

a = true
b = false

if a
    println "a is true"
else if b
    println "b is true"
end
Output:
a is true

Neko

Neko includes a bool boolean data type, true and false. Conditional execution flow only reacts to bool, numeric values test as false as are string literals.

Neko also includes two low level builtins: $not(value) and $istrue(value). These return bool results. $not returning true if value is false, 0 or null. $istrue returning true if value is not false, not 0 and not null.

/* boolean values */
$print(true, "\n");
$print(false, "\n");

if 0 {
  $print("literal 0 tests true\n");
} else {
  $print("literal 0 tests false\n");
}

if 1 {
  $print("literal 1 tests true\n");
} else {
  $print("literal 1 tests false\n");
}

if $istrue(0) {
  $print("$istrue(0) tests true\n");
} else {
  $print("$istrue(0) tests false\n");
}

if $istrue(1) {
  $print("$istrue(1) tests true\n");
} else {
  $print("$istrue(1) tests false\n");
}
Output:
prompt$ nekoc boolean.neko
prompt$ neko boolean
true
false
literal 0 tests false
literal 1 tests false
$istrue(0) tests false
$istrue(1) tests true

Nemerle

In Nemerle, boolean values are held in variables of type bool, and can be either true or false. Comparison expressions evaluate to boolean values as well.

NetRexx

NetRexx inherits boolean functionality directly from the Java virtual machine with the exception that the true and false keywords are not defined to the language. Defining true and false variables can lead to name collisions during compilation so a simple expedient is to define boolean functions isTrue and isFalse to return the appropriate values.

/* NetRexx */
options replace format comments java crossref savelog symbols nobinary

bval = [1, 0, 5, 'a', 1 == 1, 1 \= 1, isTrue, isFalse]

loop b_ = 0 for bval.length
  select case bval[b_]
    when isTrue  then say bval[b_] 'is true'
    when isFalse then say bval[b_] 'is false'
    otherwise         say bval[b_] 'is not boolean'
    end
  end b_

method isTrue public static returns boolean
  return (1 == 1)

method isFalse public static returns boolean
  return \isTrue
Output:
1 is true
0 is false
5 is not boolean
a is not boolean
1 is true
0 is false
1 is true
0 is false

Nim

if true: echo "yes"
if false: echo "no"

# Other objects never represent true or false:
if 2: echo "compile error"

Oberon-2

VAR
  a,b,c: BOOLEAN;
...
  a := TRUE;
  b := FALSE;
  c := 1 > 2;

Objeck

Objeck has a Bool type that is set to either true or false. By default boolean types are initialized to false. The boolean type also allows methods to be invoked, which perform simple conversions or print given values.

Object Pascal

In addition to the Boolean type defined by standard Pascal, object Pascal defines the types byteBool, wordBool and longBool, having a sizeOf one, two, or four bytes respectively. They were introduced primarily to ease interfacing with code written in other languages, such as C. These types only have ord(false) defined as zero, and any other ordinal value represents true.

Nonetheless, Boolean is the preferred type.

See also Delphi and Free Pascal

Objective-C

Objective-C follows pretty much the same rules as C. In addition to C, Objective-C has a BOOL boolean type, with values YES for true and NO for false. Objective-C also adds several special types of pointers; for pointers to objects (values of type id), the nil pointer is false, everything else is true; for pointers to classes (values of type Class), the Nil pointer is false, everything else is true.

OCaml

OCaml defines a built-in data type bool, which has exactly two members, represented by the keywords true and false:

type bool = false | true

In addition to all the functionality of any other OCaml algebraic data type (e.g. pattern matching), and the functionality of any other OCaml data type (e.g. comparisons false = false, false < true, etc.), bool is also used in the guards in pattern matching (“when”) and if and while syntaxes.

As with any other OCaml data type, there are no automatic conversions of other types to bool.

Octave

Octave uses true (1) and false (0). The class of a variable holding a boolean value is logical, which however can be casted to a numeric class, so that r = true; r * 2 gives 2 as result. Any non-zero value is interpreted as true, and 0 as false.

Oforth

Oforth uses true (1) and false (0)

Any non-zero value is interpreted as true, and 0 as false.

Ol

#true is True, #false is False; #t is synonym for #true, #f is synonym for #false.

In conditionals everything that is not #false is True.

p.s. Empty lists - '() - in conditionals is True.

ooRexx

.true or 1 are true, .false or 0 are false

Order

Order supplies the keywords 8true and 8false. Other types are not supposed to automatically convert to any boolean value (in practice some may do so due to implementation quirks, but this is not reliable).

Oz

true and false are the only boolean values. No other values are automatically converted to bool.

PARI/GP

Generally, false is 0 and true is nonzero. Certain other values also behave as false, like the vector [0]. Built-in boolean functions use 0 and 1 (but note that some functions like ispower are not boolean!).

The details of what is considered true or false is contained in see the function gequal0:

  • An integer (t_INT), polynomial (t_POL), power series (t_SER), or element of a finite field (t_FFELT) is false if and only if it is 0.
  • A real number (t_REAL) or complex number (t_COMPLEX) is false if and only if its absolute value rounds to 0 at the object's precision. Note that this can make nonzero complex numbers (with tiny norm) false.
  • An integer mod m (t_INTMOD) is false if and only if its residue class is 0, i.e., if lift(x) is 0.
  • A p-adic number (t_PADIC) is false if and only if it is zero up to the object's p-adic precision is 0, i.e., if lift(x) is 0.
  • A vector (t_VEC), column vector (t_COL), or matrix (t_MAT) is false if and only if all of its components are 0. Note that [] is thus false.
  • t_QUAD, t_POLMOD, t_RFRAC

Pascal

Pascal defines the type Boolean as a “special” enumeration type with exactly two elements: false and true. It is guaranteed that ord(false) is 0 and ord(true) is 1.

There is no automatic conversion from integer values to Boolean values, as it is prevalent in many other languages. Instead, one has to write a Boolean expression, for example myInteger <> 0 in order to get an assignment-compatible type.

See also Delphi, Free Pascal, and Object Pascal

Perl

my $x = 0.0;
my $true_or_false = $x ? 'true' : 'false';     # false

or

my $x = 1;          # true

my $true_or_false;

if ($x) {
    $true_or_false = 'true';
}
else {
    $true_or_false = 'false';
}

The values in Perl that are false are: 0 (as a number (including 0.0), or as the string '0', but not the string '0.0'), the empty string '', the empty list (), and undef. Everything else is true. See perlsyn.

Short circuit evaluations

Boolean comparison of zero against itself gives a value of one, but Perl uses short circuit evaluations, so any true or false value may be returned from a boolean expression:

print (7 && 2);  # 2, rather than 1(true)
print (2 && 7);  # 7, rather than 1(true)
print (7 xor 2); # empty string, rather than 0(false)
print ('apples' && 'pears');  # pears, rather than 1(true)
print ('apples' xor 'pears'); # empty string, rather than 0(false)

Objects

Objects may break these rules at will via overloading.

There are no keywords for true and false

Perl has no builtin "true" or "false" keywords. An old trick of using them as bareword strings is strongly discouraged in modern Perl.

Special cases

As a special case, literal 1s and 0s will never cause a "Useless use of a constant in void context" warning. Another special case worth pointing out here is that the string '0 but true' won't provoke a warning if it's used as a number.

Phix

Zero is false, any other number is true. Attempting to use a string or sequence as a boolean is assumed to be a programming logic blunder and causes a fatal run-time error.

Conditions such as if length(s) then are permitted, but the more explicit if length(s)!=0 then is generally preferred, and conversely, if flag then is to be preferred over if flag=true then. Comparison operators evaluate to 1(true) or 0(false). A boolean test is inverted by preceding it with the keyword not. The null character ('\0') is considered false, all other characters are deemed true. The builtin constants TRUE/FALSE and their aliases True/true/False/false may also be used.

There is however a gotcha in JavaScript, and hence pwa/p2js, in that true !== 1 and false !== 0. In almost all other respects, true is 1 and false is 0, for instance 1+true evaluates to 2, just like desktop/Phix. It is only direct comparison for equality of booleans and numbers using an infix operator which fails, and I suppose you could argue that is a programming logic blunder, by which I mean in a particular source file of a specific application, rather than in the (Phix or JavaScript) programming language definition. There is no such issue with equal() and compare(), which pwa/p2js automatically maps to when needed, that is except for bool vs number, which is difficult because in desktop/Phix those are the same thing. Thankfully, there are very few places anyone ever actually compares bools against 0 and 1 using an infix operator.

The following example illustrates, and also emphasies the subtlety of the issue (no difference whatsoever if c, d, e, f are defined as bool):

with javascript_semantics
for i=1 to 3 do
    integer c = (i==2),         -- fine
            d = (c==1),         -- oops
            e = (c==true),      -- fine
            f = equal(c,1)      -- fine, ditto equal(c,true)
    printf(1,"%d==2:%5t(%d) ==1:%5t, eq1:%5t, ==true:%5t\n",
              {i,     c, c,       d,       e,          f})
end for
--
-- output on desktop/Phix: 1==2:false(0) ==1:false, eq1:false, ==true:false
--                         2==2: true(1) ==1: true, eq1: true, ==true: true
--                         3==2:false(0) ==1:false, eq1:false, ==true:false
--
-- output on pwa/p2js:     1==2:false(0) ==1:false, eq1:false, ==true:false
--                         2==2: true(1) ==1:false, eq1: true, ==true: true
--                         3==2:false(0) ==1:false, eq1:false, ==true:false
--

PHP

The values in PHP that are false are: FALSE, NULL, the number 0 (as an integer 0, float 0.0, or string '0', but not the string "0.0"), the empty string "", the empty array array(), and "SimpleXML objects created from empty tags"(?).

Everything else is true. The keyword TRUE exists. [1]

Picat

Picat has the built-in true/0 for true (it always succeeds) and false/0 (or fail/0) for false. false/0 (/fail/0) can be used to generate other solutions through backtracking.

go ?=>
  member(N,1..5),
  println(N),
  fail, % or false/0 to get other solutions
  nl.
go => true.
Output:
1
2
3
4
5

In the Picat shell, truth is represented as "yes" and false as "no".

Picat> 2==2

yes

Picat> 2==3

no

PicoLisp

Like in all Lisps, the symbol 'NIL' denotes "false", any other value "true". PicoLisp also uses NIL as the empty list, so the empty list is false.

Some functions return the symbol 'T' for "true" if no other useful (non-NIL) value is available in the given context. Note that 'NIL' and 'T' are written in uppercase letters (PicoLisp is case-sensitive).

Pike

> 0;
(3) Result: 0
> false;
(4) Result: 0
> 0;
(6) Result: 0
> !true;
(7) Result: 0
> true;
(8) Result: 1
> 1;
(9) Result: 1
>

PL/I

True is '1'b and false is '0'b.

Declare x bit(1);
x='1'b; /* True */
x='0'b; /* False */

Using the macro facility one can define reasonable symbols for true and false

*process source attributes xref macro or(!);
 tf: proc options(main);
 %Dcl true char; %true='''1''b';
 %Dcl false char; %false='''0''b';
 If true Then
   Put Skip list('That''s true');
 If false Then
   Put Skip List('ERROR');
 Else
   Put Skip List('false was recognized');
 End;
Output:
That's true
false was recognized

PL/M

In PL/M, even numbers are falsy and odd numbers are truthy. That is to say, conditional expressions test only the low bit of the value.

IF 0 THEN /* THIS WON'T RUN */;
IF 1 THEN /* THIS WILL */;
IF 2 THEN /* THIS WON'T */;
IF 3 THEN /* THIS WILL */;

Canonically, false is represented by 0 (all bits clear), and true by 0FFH (all bits set). These are the values that conditional operators (like =) return.

DECLARE A BYTE;
A = 4 < 5;
/* A IS NOW 0FFH */

Boolean literals are not included by default, but it is not uncommon for programmers to define them by hand:

DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH';

Plain English

Boolean values are called flags. The flag literals are yes and no. You can set and clear flags.

Pony

Boolean values are true and false. Conditions must have type Bool, i.e. they are always true or false.

PostScript

Predefined constants are:

true
false

PowerShell

Two automatic variables exist for this purpose:

$true
$false

However, nearly everything can be converted to a boolean value, as detailed in the following list:

  • any non-zero number evaluates to true, zero evaluates to false
  • any non-empty string evaluates to true, an empty string evaluates to false
  • an empty array evaluates to false
  • an array containing exactly one item evaluates to whatever the only item evaluates to
  • any array with more than one item evaluates to true
  • a reference to any object evaluates to true, $null evaluates to false

Python

Python has a boolean data type with the only two possible values denoted by True and False.

The boolean type is a member of the numeric family of types (specifically a subclass of int), and when used in a numeric, but not boolean context, True has the value one and False the value zero. Also hash(True) == hash(1) and same goes for False and 0. Conversely, when numbers are used in a boolean context, zero is false and anything other than zero is true. (Note however, that True is equal to 1, so for example True + True != True.)

In a boolean context, Python extends what is meant by true and false by accepting empty collection types, such as an empty dict or an empty list as being False, and non-empty collection types as being True, so in an if statement one might branch on a list which would be the same as testing if the list had any contents.

In Python 2, a user-created class that defines a __nonzero__ method to return False or 0, or whose __len__ method returns 0, will be treated as False, otherwise the instance is treated as True. In Python 3, the magic method __nonzero__ has been changed to __bool__, which can only return values of type bool (not even int or None).

None is also False in a boolean context.

Some examples:

>>> True
True
>>> not True
False
>>> # As numbers
>>> False + 0
0
>>> True + 0
1
>>> False + 0j
0j
>>> True * 3.141
3.141
>>> # Numbers as booleans
>>> not 0
True
>>> not not 0
False
>>> not 1234
False
>>> bool(0.0)
False
>>> bool(0j)
False
>>> bool(1+2j)
True
>>> # Collections as booleans
>>> bool([])
False
>>> bool([None])
True
>>> 'I contain something' if (None,) else 'I am empty'
'I contain something'
>>> bool({})
False
>>> bool("")
False
>>> bool("False")
True

Quackery

Translation of: Forth

In conditionals, zero is false, non-zero is true. There are predefined words for the canonical forms, false returns zero and true returns 1.

R

Similarly to Octave, R uses TRUE and FALSE, kept in variable of class logical, which is silently casted to 1 (TRUE) or 0 (FALSE) if used as numeric value. The opposite is also true: the value 0 can be used as FALSE, and non-zero numbers as TRUE.

The values T and F are given the values TRUE and FALSE respectively (for compatibility with S-Plus), though these may be changed to other values by the user.

Racket

Racket has the standard Scheme Boolean values #t and #f, and will also accept #true and #false. This is a literal syntax, so it can be used anywhere including in quoted positions. There are also bindings for true and false (but of course when these are quoted, the result is plain symbols). Like other Scheme descendants, many conditional constructs treat any non-false value as "truthy." So, for instance,

(cond ([(< 4 3) 'apple]
       ['bloggle 'pear]
       [else 'nectarine])

... evaluates to 'pear, because 'bloggle is not false.

Raku

(formerly Perl 6)

Works with: Rakudo version 2015.12

Raku provides an enumeration Bool with two values, True and False. Values of enumerations can be used as ordinary values or as mixins:

my Bool $crashed = False;
my $val = 0 but True;

For a discussion of Boolean context (how Raku decides whether something is True or False): https://docs.raku.org/language/contexts#index-entry-Boolean_context.

Raven

Raven considers 0 as FALSE, -1 as TRUE

TRUE print
FALSE print
2 1 > print   # TRUE (-1)
3 2 < print   # FALSE (0)
42 FALSE !=   # TRUE (-1)

REBOL

REBOL uses values of type logic! to represent boolean values. A boolean value can be 'true' or 'false', which also happen to be understood as predefined constants. Other constants are also provided to improve program readability:

logic! Constants
True False
true false
yes no
on off
any [block! series! date! number! string! ...] none

As the last true value implies, pretty much any other type will evaluate to true. This is important to remember if you're used to a language where the value "0" is considered to be false -- in REBOL, it's true.

ReScript

A ReScript boolean has the type bool and can be either true or false.

ReScript's true/false compiles into a JavaScript true/false.

Retro

Zero is false and non-zero is true. Comparison functions return -1 for true and 0 for false.

REXX

The REXX language enforces the values for   true   and   false,   only the two values are valid:

  • 0     (zero)   [for false]
  • 1     (one)     [for true]

The following aren't   true   or   false:

  • 0.
  • 0.0
  • 00
  • 1.
  • 1.0
  • 001
  • +1
  • 2
  •       (a null value, that is, length=0)
  • any value with a blank before/in/after the value.

simplistic

 true = 1
false = 0

spruced up

Some programmers like to "spruce up" such a simple assignment:

true  = (1=1)
false = (1=0)

more exactitudeness

true  = (1==1)
false = (1==0)

oblique

true  = (1==1)
false = \true

[The parentheses aren't necessary in all of the above versions.]

Some REXX interpreters allow the   NOT   (¬) character for negation:

false = ¬true

esoteric

true  =            1984  =  1984
false =           'war'  =  'peace'
false =       'freedom'  =  'slavery'
false =     'ignorance'  =  'strength'

Of course, in Orwellian terms, the above   false   statements are   true,   but REXX isn't an Eric Arthur Blair reader.

Ring

x = True
y = False
see "x and y : " + (x and y) + nl
see "x or y : " + (x or y) + nl
see "not x : " + (not x) + nl

Rockstar

There are several synonyms for true and false. These include yes and no, or right and wrong. Therefore, to make a variable called Alice true and a variable called Bob false, you can write this.

Alice was right.
Bob was wrong.

RPL

There is no boolean variable type in RPL. Boolean values are real numbers, zero meaning 'FALSE' and any other value meaning 'TRUE'; built-in boolean operators and functions always return 1 for TRUE. RPL users have also access to boolean registers named flags, identified by a number, that can be cleared, set or tested.

Works with: Halcyon Calc version 4.2.7
1 == 1  
1 == 2
≪ IF 42 THEN "TRUE" ELSE "FALSE" END ≫ EVAL
14 CF 14 FS?
14 SF 14 FS?
Output:
5: 1
4: 0
3: "TRUE"
2: 0
1: 1

Ruby

The only values in Ruby that are false are: false and nil. They have synonyms FALSE and NIL.

Everything else is true. Constants true (and TRUE) exist. Note for Python and Perl users: unlike Python, in Ruby, the number 0, the empty string, the empty array, and the empty hash, etc. are all true; you can instead use the zero? method to test for 0, and the .empty? method to test for an empty sequence.

false, nil and true are singleton instances of classes FalseClass, NilClass and TrueClass respectively. [2]

Rust

fn main() {
    // Rust contains a single boolean type: `bool`, represented by the keywords `true` and `false`.
    // Expressions inside `if` and `while` statements must result in type `bool`. There is no
    // automatic conversion to the boolean type.

    let true_value = true;
    if true_value {
        println!("foo is {}.", true_value);
    }

    let false_value = false;
    if !false_value {
        println!("bar is {}.", false_value);
    }
}
Output:
foo is true.
bar is false.

Sather

The BOOL type can be true or false. Sather never implicitly does casting of a type in another, so numeric value or other types cannot be used (implicitly) as boolean value; nonetheless an explicit "cast" can be done:

v:BOOL := true; -- ok
i:INT := 1;
v := 1; -- wrong 
if i then ... end; -- wrong: if requires a bool!
-- BUT
v := 1.bool; -- ok
if i.bool then ... end; -- ok

In this case, 0.bool is false, and n.bool with n not equal to 0 is true.

S-BASIC

Although S-BASIC has no explicit boolean data type, it allows integer, real, fixed, string, and character variables to hold the results of boolean operations and to represent true and false conditions in IF, WHILE, and REPEAT statements. For types real.double, real, and fixed, a value of zero is false, and any non-zero value is true. For integers, the value 0 is treated as false, while -1 (or FFFFH), the bit-wise negation of zero, is treated as true. For characters and strings, 'Y', 'y', 'T', and 't' are treated as true, while 'N', 'n', 'F', and 'f' are treated as false. (For strings, only the first character is considered.) For convenience, the $CONSTANT compiler directive can be used to provide values for "true" and "false".

$constant true = 0FFFFH
$constant false = 0

var a, another = char
var b, adult, age = integer
var c = real

repeat
   begin
     input "Applicant's age in years"; age
     adult = (age >= 18)
     if adult then
        print "Applicant has full access"
     else
        print "Applicant has restricted access"
     input "Do another (y/n)"; another
   end
until not another

a = (2 > 3)
b = (2 > 3)
c = (2 > 3)
print "2 > 3 as char: "; a
print "2 > 3 as int : "; b
print "not (2 > 3)  : "; not b
print "2 > 3 as real: "; c
print "not (2 > 3)  : "; not c
 
end
Output:
Applicant's age in years? 19
Applicant has full access
Do another (y/n)? n
2 > 3 as char: F
2 > 3 as int : 0
not (2 > 3)  :-1
2 > 3 as real: 0
not (2 > 3)  :-1

Scala

Booleans in Scala are given by the literals true and false, case sensitive, which are the only instances of the class Boolean.

Scheme

The only value in Scheme that is false is #f.

Everything else (including the empty list, unlike Lisp) is true. The constant #t represents the canonical true value.

Seed7

Seed7 defines the type boolean. The only values of boolean are TRUE and FALSE. There are no automatic conversions from any other types into boolean, and it is a compile-time error to use any type other than boolean in a place that expects a boolean (e.g. if-statement condition, while-statement condition, operand of a logical operator, etc.).

Self

Self has two objects, true and false.

SenseTalk

True, Yes, and On are true; False, No, Off and Empty (an empty string) are false.

repeat with each item of [True, False, Yes, No, On, Off, ""]
	put it & " is " & (it is true)
end repeat
Output:
True is True
False is False
Yes is True
No is False
On is True
Off is False
 is False

Sidef

Sidef defines the true and false boolean values, which are part of the Bool type.

var t = true;
var f = false;

In conditional expressions, anything that evaluates to zero or nothing is considered false, including empty arrays and empty hashes.

if (0 || "0" || false || nil || "" || [] || :()) {
    say "true"
} else {
    say "false";
}
Output:
false

Simula

Simula has true and false keywords, representing the only values of type boolean. There are no automatic conversions from any other types into boolean, and it is a compile-time error to use any type other than boolean in a place that expects a boolean (e.g. if-statement condition, while-statement condition, operand of a logical operator, etc.).

Slate

Use True or False.

Smalltalk

Use "true" and "false".
Smalltalk uses the Boolean class, which has two subclasses (True and False). true and false are singleton instances of those classes. E.g. an expression like 5 = 5 returns true.

SNUSP

Zero is false and non-zero is true, as used by the sole skip-if-zero operator (?).

$!/?\=false= + =true=#
  \-/

SPL

In SPL zero is false, any other value is true.

Standard ML

Standard ML defines a top-level data type bool, which has exactly two members, true and false:

datatype bool = false | true

In addition to all the functionality of any other Standard ML algebraic data type (e.g. pattern matching, equality false = false), bool is also used in if and while syntaxes.

As with any other Standard ML data type, there are no automatic conversions of other types to bool.

Stata

Stata uses the values 0 for "false" and 1 for "true". In expressions involving boolean operators, any nonzero numeric value (including missing values) is considered true.

Swift

Swift defines a built-in data type Bool, which has two values, represented by the keywords true and false. There is no conversion between booleans and other data types. Conditionals require a type that conforms to the BooleanType protocol, which provides a conversion to Bool for that type; types that conform include Bool and some other types.

Tcl

True values
1 (or other non-zero number, e.g., 42), true, yes, on
False values
0 (or other zero number, e.g., 0.0), false, no, off

Any of these values may be abbreviated, and mixed-case spellings are also acceptable. [3] Any other value gives an error. In an interactive tclsh session:

% if {""} then {puts true} else {puts false}
expected boolean value but got ""

Test for the boolean value of a string can be stuff like

if {[string is false -strict $string]} ...

which will test for "no" or "NO" or "0" or "False" or ...

Trith

The boolean constants are true and false. In a conditional context, the only false values are false and nil -- every other value is true.

UNIX Shell

The traditional Bourne shell does not provide a reserved keyword for true or false.

Truth is determined by exit codes rather than values

The evaluation of true and false within the shell is different to the evaluation of truth from within a high level language. Within the shell, a truth is based on the exitcode of the last command in the evaluation block:

  • An exitcode of zero is considered to be a true condition
  • An exitcode of nonzero is considered to be a false condition

In the following example, after running the test command, the then syntactical component runs the optional branch if an exitcode is of zero determined:

if
  echo 'Looking for file'  # This is the evaluation block
  test -e foobar.fil       # The exit code from this statement determines whether the branch runs                            
then
  echo 'The file exists'   # This is the optional branch
  echo 'I am going to delete it' 
  rm foobar.fil
fi

In some later shells, the values true and false are defined, respectively, as a return code of 0 and a return code of greater-than zero. While there are built-in functions for each of these values, booleans are most commonly the result of a test or a process termination.

Works with: bash
Works with: ksh
true && echo "true" || echo "false"

Ursa

Ursa has the boolean data type which can be declared using the declare (or decl) function.

decl boolean bool

Boolean values can be set to either true or false, or the result of an expression.

set bool true
# same as
set bool (= 2 2)

or

set bool false
# same as
set bool (not (= 2 2))

VBA

VBA has a boolean type. As an integer False is 0 and anything else is True. However True converts to -1. Booleans are False by default.

Dim a As Integer
Dim b As Boolean
Debug.Print b
a = b
Debug.Print a
b = True
Debug.Print b
a = b
Debug.Print a
Output:

Output of above lines:

False
0
True
-1

VBScript

VBScript has the boolean subdatatype and also the two constants True and False. When converting an integer to a boolean, 0 is False and anything not equal to 0 is True.

a = True
b = False
Randomize Timer
x = Int(Rnd * 2) <> 0
y = Int(Rnd * 2) = 0
MsgBox a & " " & b & " " & x & " " & y
Output:
True False True False

Vim Script

A non-zero Number is true, 0 is false.

Since a String is converted automatically to a Number when necessary, the following will print "false" because "foo" is converted to 0:

if "foo" 
    echo "true"
else
    echo "false"
endif

V (Vlang)

V has a bool type, with literal values for true and false. Numeric values are not used in conditional statements. 0 is not treated as false, and non-zero does not mean true, in V.

// Boolean Value, in V
// Tectonics: v run boolean-value.v
module main

// V bool type, with values true or false are the V booleans.
// true and false are V keywords, and display as true/false
// Numeric values are not booleans in V, 0 is not boolean false
pub fn main() {
    t := true
    f := false

    if t { println(t) }

    // this code would fail to compile
    // if 1 { println(t) }

    if 0 == 1 { println("bad result") } else { println(f) }
}
Output:
prompt$ v run boolean-value.v
true
false

WDTE

WDTE has a built-in boolean type, the two values of which are exposed by the std package's true and false functions. In general, however, built-in conditional functionality, such as switch expressions, considers any value that is not true to be false.

let io => import 'io';
let ex => switch 'this is irrelevant for this example' {
  false => 'This is, obviously, not returned.';
  'a string' => 'This is also not returned.';
  true => 'This is returned.';
};
ex -- io.writeln io.stdout;

The above prints "This is returned."

Wren

Wren has a core class, Bool, which has two instances true and false which are also reserved words in the language.

This class has two methods: the operator ! which returns the logical complement of its receiver and toString which returns its string representation.

var embed = true
System.printAll([embed, ", ", !embed, ", ", "Is Wren embeddable? " + embed.toString])
Output:
true, false, Is Wren embeddable? true

XLISP

Boolean "false" may be represented by #F, #!FALSE, NIL, or the empty list; any other value is counted as true in conditional expressions, but it is also possible to represent the Boolean value "true" using your choice of the symbols #T, #!TRUE, and T. All these symbols are case-insensitive. Note that T, unlike the others, is a variable: it is bound by default to the constant #T, but you can (although you shouldn't) assign it any other value including "false" (by doing something like (setq t nil)). Boolean values are printed as #T and ().

XPL0

An integer value equal to 0 is false, and a value not equal to 0 is true. Relational operations evaluate to 0 for false and -1 for true. The command word 'true' equals -1, and 'false' equals 0.

XSLT

<xsl:if test="true() or false()">
  True and false are returned by built-in XPath functions.
</xsl:if>
<xsl:if test="@myAttribute='true'">
  Node attributes set to "true" or "false" are just strings. Use string comparison to convert them to booleans.
</xsl:if>
<xsl:if test="@myAttribute or not($nodeSet)">
  Test an attribute for its presence (empty or not), or whether a node set is empty.
</xsl:if>

Z80 Assembly

There are no official constants for True or False, however the common convention is to use 0 for false and nonzero for true. In reality, any mutually exclusive condition will work. True/False can be tested using a variety of instructions. The most common are CP and BIT but in certain cases it can be done faster using AND or even RRCA.

All of the following can be used to test if the rightmost bit of a byte is 1.

BIT 0,A
jr nz,true
;;;;;;;;;;;;;;;;
AND 1
jr nz,true
;;;;;;;;;;;;;;;;
RRCA
jr c,true

Of these three methods, the last one is the fastest and takes the least amount of bytes to encode. However, it does destroy the variable, which may not be an option depending on what you need to do with that data later. BIT is slower than the rest but doesn't alter registers or memory, just the flags, which is sometimes exactly what you need.

zkl

a:=True;
b:=False;
True.dir();
Output:
True : Bool
Methods:
   -- BaseClass Method Property __sGet __sSet copy create dir fp fp1 fp2 
   fpM fpN isChildOf isInstanceOf isType len method noop print println 
   property resolve toBool toData toFloat toInt toList toString toType 
Properties:
   -- createReturnsSelf fullName id isContainer isThreadSafe itype methods 
   name numObjects oID otype properties size type typeID vaultPath

zonnon

var
	a,b,c: boolean;
begin
	a := false;
	b := true;
	c := 1 > 2;
...