Cpp If
## C++ `if` Statement
In C++, the `if` statement is the most fundamental decision-making statement. It is used to decide whether a specific statement or block of code will be executed based on a given condition.
---
### Introduction
An `if` statement consists of a boolean expression followed by one or more statements.
* If the boolean expression evaluates to **true**, the block of code inside the `if` statement is executed.
* If the boolean expression evaluates to **false**, the block of code inside the `if` statement is skipped, and the program continues executing the code immediately following the `if` block.
> **Note on Truth Values in C++:**
> In C++, any **non-zero** and **non-null** value is implicitly treated as `true`, while **zero** (`0`) or `nullptr` is treated as `false`.
---
### Syntax
The syntax of an `if` statement in C++ is as follows:
```cpp
if (boolean_expression) {
// Statement(s) will execute if the boolean expression is true
}
```
#### How it Works:
1. The program evaluates the `boolean_expression` inside the parentheses.
2. If the expression evaluates to `true` (or a non-zero value), the statements inside the curly braces `{}` are executed.
3. If the expression evaluates to `false` (or zero), the program skips the curly braces and executes the next statement in sequence.
---
### Flowchart
The execution flow of an `if` statement can be visualized as follows:
```
β
βΌ
/===============\
< Is Condition >
< True? >
\===============/
β β
β Yes β No
βΌ β
β
β β
βΌ βΌ
```
---
### Code Example
Below is a complete C++ program demonstrating the usage of the `if` statement:
```cpp
#include
using namespace std;
int main () {
// Local variable declaration
int a = 10;
// Check the boolean condition using an if statement
if (a < 20) {
// If the condition is true, print the following
cout << "a is less than 20" << endl;
}
cout << "The value of a is: " << a << endl;
return 0;
}
```
#### Output:
When the above code is compiled and executed, it produces the following output:
```text
a is less than 20
The value of a is: 10
```
---
### Best Practices and Considerations
1. **Use Curly Braces `{}`:**
If the body of the `if` statement contains only a single line of code, the curly braces are optional. However, it is highly recommended to always use curly braces to prevent logical bugs when adding more statements later.
*Avoid this:*
```cpp
if (a < 20)
cout << "a is less than 20" << endl; // Only this line is conditional
cout << "This always prints!" << endl; // This runs regardless of the condition!
```
2. **Avoid Accidental Assignment:**
Be careful not to confuse the assignment operator (`=`) with the equality comparison operator (`==`).
*Incorrect:*
```cpp
if (a = 20) { // This assigns 20 to 'a' and evaluates to true!
// Unexpected behavior
}
```
*Correct:*
```cpp
if (a == 20) { // This correctly compares 'a' with 20
// Conditional block
}
```
YouTip