Share operator ternary c++

## Nhà điều hành Ternary C ++

[Liên kết đến bài viết tham khảo]

Toán tử ternary trong C ++ là một cách viết tắt để viết một câu lệnh if-else.Nó có hình thức của `expr1?expr2: expr3`, trong đó `expr1` là biểu thức boolean,` expr2` là biểu thức sẽ được đánh giá nếu `expr1` là đúng và` expr3` là biểu thức sẽ được đánh giá nếu `expr1` là sai.

Ví dụ: mã sau sử dụng toán tử ternary để in "Hello World" nếu biến `X` bằng 1 và" Goodbye World "nếu không:

`` `C ++
int x = 1;

if (x == 1) {
std :: cout << "Hello World" << std :: endl;
} khác {
std :: cout << "Goodbye World" << std :: endl;
}
`` `

Mã này có thể được viết lại bằng toán tử ternary như sau:

`` `C ++
int x = 1;

std :: cout << (x == 1? "Hello World": "Goodbye World") << std :: endl;
`` `

Toán tử ternary là một cách thuận tiện để viết các câu lệnh ngắn, có điều kiện ngắn gọn.Tuy nhiên, điều quan trọng là chỉ sử dụng nó khi điều kiện đơn giản và các biểu thức ngắn.Nếu điều kiện hoặc biểu thức là phức tạp, tốt hơn là sử dụng câu lệnh if-else.

## hashtags

* #C ++
* #Nhà điều hành
* #Ternary
* #Conditional
* #Tuyên bố
=======================================
## Operator Ternary C++

[Link to reference article]

The ternary operator in C++ is a shorthand way to write an if-else statement. It takes the form of `expr1 ? expr2 : expr3`, where `expr1` is a boolean expression, `expr2` is the expression that will be evaluated if `expr1` is true, and `expr3` is the expression that will be evaluated if `expr1` is false.

For example, the following code uses a ternary operator to print "Hello world" if the variable `x` is equal to 1, and "Goodbye world" if it is not:

```c++
int x = 1;

if (x == 1) {
std::cout << "Hello world" << std::endl;
} else {
std::cout << "Goodbye world" << std::endl;
}
```

This code can be rewritten using a ternary operator as follows:

```c++
int x = 1;

std::cout << (x == 1 ? "Hello world" : "Goodbye world") << std::endl;
```

The ternary operator is a convenient way to write short, concise conditional statements. However, it is important to use it only when the condition is simple and the expressions are short. If the condition or expressions are complex, it is better to use an if-else statement.

## Hashtags

* #C++
* #Operator
* #Ternary
* #Conditional
* #Statement
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top