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
isRunning
is assigned the valuetrue
. - The
if
statement checks ifisRunning
evaluates 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
count
is incremented and printed. - The
break
statement exits the loop whencount
reaches 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
isConnected
istrue
, andisAuthenticated
isfalse
. - The logical expression
isConnected && !isAuthenticated
evaluates totrue
, so theif
block executes. - The message is printed to indicate the user’s state.
Key Points to Remember about true
Keyword
- The
true
keyword represents the Boolean value for “true.” - It is part of the
bool
data type and is equivalent to1
in arithmetic expressions. - It is commonly used in control flow statements like
if
,while
, andfor
. - In infinite loops,
true
can be used as the condition to ensure continuous execution until explicitly broken. - Using
true
makes code more readable and aligns with C++’s type-safe practices.