This commit is contained in:
21
Career/Theory/Ternary Operator.md
Executable file
21
Career/Theory/Ternary Operator.md
Executable file
@@ -0,0 +1,21 @@
|
||||
---
|
||||
note type:
|
||||
- theory
|
||||
date: 2026-06-19
|
||||
done: true
|
||||
---
|
||||
The **ternary operator**, also known as the **conditional operator**, is a concise way to write an **if-else** statement in a single line by evaluating a **condition** and returning one of two values. It is called "ternary" because it operates on **three operands**: the condition, the expression to execute if true, and the expression to execute if false.
|
||||
|
||||
The standard syntax is:
|
||||
|
||||
```
|
||||
condition ? expression_if_true : expression_if_false
|
||||
```
|
||||
|
||||
Key characteristics include:
|
||||
|
||||
- **Short-Circuit Evaluation**: Only the expression corresponding to the evaluated condition is executed.
|
||||
- **Readability**: It enhances code brevity for simple logic but can reduce maintainability if nested excessively.
|
||||
- **Language Support**: It is widely supported in C-like languages (C, C++, Java, JavaScript, C#) and has variations in others (e.g., Python uses `value_if_true if condition else value_if_false`).
|
||||
- **Performance**: It generally has negligible performance differences compared to standard if-else blocks, as modern compilers optimize both similarly.
|
||||
- **Association**: In most languages, the operator is **right-associative**, allowing for chained conditions similar to `if...else if...else` chains.
|
||||
Reference in New Issue
Block a user