From c036904e86310e456a3f32afcaa43779d88561bd Mon Sep 17 00:00:00 2001 From: Morgan McLain-Smith Date: Tue, 15 Jan 2019 16:43:30 -0500 Subject: [PATCH] simplified ternary operator article (#33077) --- guide/english/c/ternary-operator/index.md | 41 +++++++++++++---------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/guide/english/c/ternary-operator/index.md b/guide/english/c/ternary-operator/index.md index 050f2eb342..6096cd6242 100644 --- a/guide/english/c/ternary-operator/index.md +++ b/guide/english/c/ternary-operator/index.md @@ -4,10 +4,22 @@ title: Ternary Operator ## Ternary Operator -Programmers use ternary operators in C for decision making inplace of conditional statements **if** and **else**. -The ternary operator is an operator that takes three arguments. The first argument is a comparison argument, the second is the result upon a true comparison, and the third is the result upon a false comparison. If it helps you can think of the operator as shortened way of writing an if-else statement. +The ternary operator in C is a shorthand for simple **if/else** statements. -Here's a simple decision-making example using **if** and **else**: +It takes three arguments: +1. An condition +2. The result if the condition evaluates to true +3. The result if the condition evaluates to false + +### Syntax + +`condition ? value_if_true : value_if_false` + +`value_if_true` and `value_if_false` must have the same type, and must be simple expressions not full statements. + +### Example + +Here's an example without the ternary operator: ```c int a = 10, b = 20, c; @@ -22,15 +34,7 @@ else { printf("%d", c); ``` -This example takes more than 10 lines, but that isn't necessary. You can write the above program in just 3 lines of code using the **ternary operator**. - -### Syntax - -`condition ? value_if_true : value_if_false` - -The statement evalutes to statement\_1 if the condition is true, and statement\_2 otherwise. - -Here's the above example re-written to use the ternary operator: +Here's the above example re-written to use the **ternary operator**: ```c int a = 10, b = 20, c; @@ -40,17 +44,20 @@ c = (a < b) ? a : b; printf("%d", c); ``` -Output of the example should be: +Both examples will output: ```c 10 ``` -`c` is set equal to `a`, because the condition `a