condition ternaire in c
Ternary Operator in C
The ternary operator in C is a conditional operator that allows you to write concise if-else statements in a single line of code. It has the following syntax:
condition ? expression1 : expression2;
Here's an explanation of each step involved in using the ternary operator:
- The
condition
is a boolean expression that evaluates to either true or false. - If the
condition
is true,expression1
is executed. - If the
condition
is false,expression2
is executed.
The value of the entire ternary expression is the value of either expression1
or expression2
, depending on the evaluation of the condition
.
Let's look at an example to illustrate the usage of the ternary operator:
int x = 10;
int y = (x > 5) ? 100 : 200;
In this example, the condition
is (x > 5)
, which evaluates to true because x
is indeed greater than 5. Therefore, the value of y
will be 100 because expression1
is executed.
If the condition
were false, the value of y
would be 200 because expression2
would be executed.
That's it! The ternary operator allows you to write compact if-else statements in C.