Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Short Handed If-else #51

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions cpp/control-statements/conditional-statements.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,45 @@ int main()
}
```
#### Check Result [here](https://onecompiler.com/cpp/3vmbg85we)

## 5. Short handed if else / Ternary Operations

There is also an abbreviation for if else called the ternary operator because it consists of three operands. Can be used to replace multiple lines of code with a single line. Often used to replace simple if else statements.
.

### Syntax

```c
variable = (condition) ? expressionTrue : expressionFalse;
```
### Example
Instead of writing
```c
#include <iostream>
using namespace std;

int main()
{
int age = 20;
if (age < 18) {
cout << "Underaged.;
} else {
cout << "Eligible to vote";
}
}
```
We can Simply Write
```c
#include <iostream>
using namespace std;

int main()
{
int age = 20;
string result = (age < 18) ? "Underaged" : "Eligible to vote";
cout << result;
}
```

#### Check Result [here](https://onecompiler.com/cpp/3ykkar3su)