Example Analysis of conditional operators and conditional expressions in C language
This article mainly introduces the example analysis of conditional operators and conditional expressions in C language, which is very detailed and has certain reference value. Friends who are interested must read it!
Conditional operators and conditional expressions
The conditional operator is the only ternary operator in the C language. The expression composed of conditional operators is called conditional expression, and its general form is as follows:
Expression 1? Expression 2: expression 3
The process of evaluating a conditional expression is as follows: first, the value of expression 1 is evaluated; if the value is true (not 0), the value of expression 2 is evaluated as the value of the conditional expression; otherwise, the value of expression 3 is evaluated as the value of the conditional expression.
Give an example
Topic description: use conditional operation to input two integers from the keyboard and output their larger values.
Examples of answers:
1#include
2int main ()
3 {
4 int max, a, b
5 printf ("Input two integers:")
6 scanf ("% d% d", & a
7 max = a > b? A: b
8 printf ("max=%d\ n", max)
9 return 0
10}
Results:
Matters needing attention
(1) conditional operators take precedence over assignment operators and are lower than all other operators.
For example: min=a > b?b*b:a*a
(2) the conditional operator is left associative.
For example: flag=a > 0?1:a==0?0:1
(3) the types of three expressions in conditional expressions can be different, and the higher type of expression 2 and expression 3 determines the type of conditional expression.
For example: max=a > baked 3.14purl 100
The above is all the content of the article "sample Analysis of conditional operators and conditional expressions in C language". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!