C++ true Keyword
The true keyword in C++ represents the Boolean value true. It is used in logical and conditional expressions to indicate a condition that evaluates to true. Along with false, it is part of the bool data type, which was introduced in C++ as part of the Standard Library.
The value of true is equivalent to 1 when used in arithmetic expressions or converted to an integer type. It plays a key role in control flow statements such as if, while, and for.
Syntax
</>
Copy
bool variable = true;
- true
- A Boolean constant representing the logical value “true.”
Examples
Example 1: Basic Usage of true
In this example, you will learn the use of true in a Boolean variable and a conditional statement.
</>
Copy
#include <iostream>
using namespace std;
int main() {
bool isRunning = true;
if (isRunning) {
cout << "The program is running." << endl;
}
return 0;
}
Output:
The program is running.
Explanation:
- The Boolean variable
isRunningis assigned the valuetrue. - The
ifstatement checks ifisRunningevaluates totrue, and the corresponding block executes. - The message is printed because the condition evaluates to
true.
Example 2: Using true in Loops
The true keyword can be used to create infinite loops, which can be exited with a break statement.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int count = 0;
while (true) {
cout << "Count: " << count << endl;
count++;
if (count == 5) {
break; // Exit the loop
}
}
return 0;
}
Output:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Explanation:
- The
while (true)loop runs indefinitely because the condition always evaluates totrue. - Inside the loop, the value of
countis incremented and printed. - The
breakstatement exits the loop whencountreaches 5.
Example 3: Using true with Logical Expressions
The true keyword can be combined with logical operators in conditional expressions.
</>
Copy
#include <iostream>
using namespace std;
int main() {
bool isConnected = true;
bool isAuthenticated = false;
if (isConnected && !isAuthenticated) {
cout << "User is connected but not authenticated." << endl;
}
return 0;
}
Output:
User is connected but not authenticated.
Explanation:
- The variable
isConnectedistrue, andisAuthenticatedisfalse. - The logical expression
isConnected && !isAuthenticatedevaluates totrue, so theifblock executes. - The message is printed to indicate the user’s state.
Key Points to Remember about true Keyword
- The
truekeyword represents the Boolean value for “true.” - It is part of the
booldata type and is equivalent to1in arithmetic expressions. - It is commonly used in control flow statements like
if,while, andfor. - In infinite loops,
truecan be used as the condition to ensure continuous execution until explicitly broken. - Using
truemakes code more readable and aligns with C++’s type-safe practices.
