Синтаксис: истина и ложь в С++
Любое целочисленное значение, кроме 0 будет эквивалентно истине. Например, 1, 2, 4, 45 — все это истина, а нуль — нет. В С++ также зарезервировано ключевое слово, обозначающее истину — true . Смотрим пример:
Значения истина и ложь специфицирует логический тип данных bool , про этот тип данных вы можете подробно прочитать в статье: Типы данных в С++.
Значение ложь (false)
В языках Си и С++ значение 0 и его эквиваленты: NULL или nullptr являются значениями ложи. Если хотите узнать, как в С++ пользоваться логическими операциями, читайте статью: Основные логические операции в С++. Может вы не знаете, что такое логические операции, тогда прочитайте эту статью: Теория логических операций.
Introduction to C Programming
Decision and Branching Concepts
Boolean Variables and Data Type ( or lack thereof in C )
- A true boolean data type could be used for storing logical values, and would only have two legal values — "true", and "false".
- C does not have boolean data types, and normally uses integers for boolean testing.
- Zero is used to represent false, and One is used to represent true.
- For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.
- To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.
- In the old days, this was done using #define:
- #define true 1
- #define false 0
- const int true = 1;
- const int false = 0;
- The type "bool" is the same as a newly defined type "_Bool"
- _Bool is an unsigned integer, that can only be assigned the values 0 or 1
- Attempting to store anything else in a _Bool stores a 1. ( Recall that C interprets any non-zero as true, i.e. 1 )
- Variables can now be declared of type "bool".
Relational Operators
- Relational operators are binary operators that evaluate the truthhood or falsehood of a relationship between two arguments, and produce a value of true ( 1 ) or false ( 0 ) as a result.
- The following table shows the 6 relational operators and their meaning, by example:
- ( Note: There should not be a space between the two equals signs in = =. I am adding one in these HTML notes so the two signs do not run together, as ==. )
- DANGER DANGER: Do not confuse the equality test operator, = =, with the assignment operator, =. It is a VERY common error to use the wrong number of equals signs, ( either too many or too few ), and the resulting code will usually compile and run but produce incorrect ( and often unpredictable ) results.
- Example: "while( i = 5 )" is an infinite loop, because i is given the value 5 by the assignment, and since this is non-zero, it is always true. The programmer probably meant to use "while( i = = 5 )", which will test whether or not i is equal to 5, and will only continue to loop as long as this is true.
- double x, y, tolerance = 1.0E-6;
- BAD: if( x = = y )
- GOOD: if( fabs( x — y ) < tolerance )
- This is particularly important when testing the stopping condition of an iterative algorithm, because otherwise the roundoff error could cause the program to run forever. WRONG: while( estimatedError != 0.0 )
Logical Operators
- Logical operators are used to combine and evaluate boolean expressions, generally in combination with the relational operators listed above.
- The following table shows the 3 logical operators and their meaning, by example:
- Note: There should not be a space between the | characters in | |, but one is being added here for clarity.
- DANGER DANGER: If you only use a single & or | instead of the double && or | |, then you get valid code that is beyond the scope of this course, but which will not do what you want.
- ! has a very high precedence, higher than the relational operators listed above. && and | | have lower precedence than the relational operators, with && having higher precedence than | |.
- Example: To determine whether x is between 5.0 and 10.0:
- INCORRECT: 5.0 < x < 10.0
- CORRECT: 5.0 < x && x < 10.0
- Question — What is the value of the incorrect expression ( regardless of the value of x ), and why?
- In a complex logical expression, the computer will stop evaluating the expression as soon as the result is known.
- "A && B" will not evaluate B if A is already false.
- "A | | B" will not evaluate B if A is already true.
- Example: "if( x != 0.0 && 1.0 / x < 10.0 )" will never divide by zero.
if-else
- "if" blocks and "if-else" blocks are used to make decisions, and to optionally execute certain code.
- The general syntax of the if-else structure is as follows:
- Either the true_block or the false_block can be either a single statement or a block of statements enclosed in
- The else clause and the false block are optional.
- In execution, the condition is evaluated for truth or falsehood.
- If the condition evaluates to true ( non-zero ), then the true_block of code is executed.
- If the condition evaluates to false ( zero ), then the false-block of code is executed if it is present.
- After one or the other block is executed, then execution continues with whatever code follows the if-else construct, without executing the other block.
-
When an if-else construct is used in the true block of another if-else, that is termed nested ifs.
switch
- In many cases, an integer valued expression must be compared against a number of possible choices, such as the following:
- In this situation a much better solution is the switch statement. The equivalent switch for the above is:
switch( variable_integer_expression ) <
case constant_integer_expression_1 :
code block 1;
break; // ( Optional — See below )
// Repeat the case sub-construct as many times as needed
default: // Optional
default code block;
break; // Not needed. Added for defensive programming only.
> // End of switch on . . .
- If the break statement is omitted from the end of a case, then execution will continue into the next case, and so on until a break is eventually encountered, or until the end of the switch is reached.
- Omitting the break statement is a common mistake.
- Sometimes the break is omitted intentionally, in order to combine cases:
The Conditional Operator
Earlier we looked at unary and binary operators under C. In addition, the C language contains one ternary operator, known as the conditional operator, ?:
- The conditional operator functions very much like an if-else construct, and the two constructs can often be used interchangeably.
- However, due to its operator status, the results of the conditional operator can also be used as part of a larger expression and/or be assigned to a variable.
- The syntax of the conditional operator is:
- The condition is first evaluated, ( along with any side effects. ) Then, either the true clause or the false clause will be executed, ( along with any side effects ), depending on whether the condition evaluates to true ( non-zero ) or false ( zero ) respectively. The value of the conditional operator as used in a larger expression is the value of whichever clause gets executed.
- Examples:
Related Topics
The following topics are not covered here, but may be found in many books on C/C++;
Using boolean values in C
C doesn’t have any built-in boolean types. What’s the best way to use them in C?
19 Answers 19
From best to worse:
Option 1 (C99 and newer)
Option 2
Option 3
Option 4
Explanation
- Option 1 will work only if you use C99 (or newer) and it’s the "standard way" to do it. Choose this if possible.
- Options 2, 3 and 4 will have in practice the same identical behavior. #2 and #3 don’t use #defines though, which in my opinion is better.
If you are undecided, go with #1!

A few thoughts on booleans in C:
I’m old enough that I just use plain int s as my boolean type without any typedefs or special defines or enums for true/false values. If you follow my suggestion below on never comparing against boolean constants, then you only need to use 0/1 to initialize the flags anyway. However, such an approach may be deemed too reactionary in these modern times. In that case, one should definitely use <stdbool.h> since it at least has the benefit of being standardized.
Whatever the boolean constants are called, use them only for initialization. Never ever write something like
These can always be replaced by the clearer
Note that these can actually reasonably and understandably be read out loud.
Give your boolean variables positive names, ie full instead of notfull . The latter leads to code that is difficult to read easily. Compare
Both of the former pair read naturally, while !notfull is awkward to read even as it is, and becomes much worse in more complex boolean expressions.
Boolean arguments should generally be avoided. Consider a function defined like this
Within the body of the function, it is very clear what the argument means since it has a convenient, and hopefully meaningful, name. But, the call sites look like
Here, it’s essentially impossible to tell what the parameter meant without always looking at the function definition or declaration, and it gets much worse as soon if you add even more boolean parameters. I suggest either
In either case, the call site now looks like
which the reader has at least a chance of understanding without dredging up the definition of foo .
boolean (bool or _Bool) datatype in C
C programming language (from C99) supports Boolean data type (bool) and internally, it was referred as _Bool as boolean was not a datatype in early versions of C. In C, boolean is known as bool data type. To use boolean, a header file stdbool.h must be included to use bool in C.
bool is an alias to _Bool to avoid breaking existing C code which might be using bool as an identifier. You can learn about _Bool here in detail.
Note if we do not include the above header file, then we need to replace bool with _Bool and the code will work as usually.
Standard logical operators AND (&&), OR(||) and NOT(!) can be used with the Boolean type in any combination.
In computer science, the Boolean data type is a data type that has one of two possible values, either TRUE or FALSE. Due to two possible values, it needs only 1 bit. In actual computing systems, the minimum amount of memory is set to a particular value (usually 8 bits) which is used (all bits as 0 or 1).
Memory
An object declared as type Bool is large enough to store the values 0 and 1.
The above code will give size 1 for bool, so generally bool store a 1 byte of memory. Note: it needs only 1 bit but takes 8 bits due to the structure of the computing system.
- true is denoted as 00000001
- false is denoted as 00000000
Declaration
To declare a variable as a boolean use:
Bool with Logical Operators
We can use logical operators with boolean.
Types of logical operators:
- && (AND): takes 2 booleans; returns true only if both operands are true else false
- || (OR): returns true if either or both of the operands are true else false
- ! (NOT): takes 1 operand; return true if operand is false and false if operand is true
Bool Array
How to convert a boolean to integer? (type casting)
A type cast is basically a conversion from one type to another.
An object declared as type Bool is large enough to store the values 0 and 1.There’s no need to cast to bool for built-in types because that conversion is implicit. On converting to other integral types, a true bool will become 1 and a false bool will become 0.
- In the old days, this was done using #define: