How to use question mark expression in C language
This article is about how to use question mark expressions in C language. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Question mark expression in C language
Question mark expression
(expression 1)? (expression 2): (expression 3)
Execute expression 2 if expression 1 is valid, otherwise execute expression 3
Give an example
Inta=5,b=3
Printf ("% d", a > btincaVlb)
Run
Execute if an is greater than b: the preceding one outputs a. Otherwise execute: the output b is followed by. In this case, the output is 5.
Points for attention
The question mark expression runs from right to left
For example
Inta=8,b=3,c=7
Printf ("d", a > Bevera > c?a:c:b > c?b:c)
It can be done in three steps.
Step 1: B > c?b:c result is c
Step 2: a > c?a:c result is a
Step 3: the results of the first two steps correspond to expression 3 and expression 2, namely a > b?a:c
The final output is an or 8
Question mark expression and comma expression
Question mark expression:
# include
Voidmain ()
{
Inta,b,c,d,e
Cedar 9
Dumb8
Scanf ("% djas% d", & a djm% d)
E = (a > b)? CRAV d
Printf ("% d\ n", e)
}
It can be understood that the whole expression after "=" can be regarded as (expression 1). If a > b, then eDec, otherwise eDead. (expression 2): (expression 3)
Comma expression:
# include
Voidmain ()
{
Inta,b,c,d,e
Cedar 9
Dumb8
Scanf ("% djas% d", & a djm% d)
E = ((a=b+c), aqd)
Printf ("% d\ n", e)
}
Make a small change based on the question mark expression to get:
The comma expression has the lowest precedence, e = ((a=b+c), aqd) first evaluates the bdistribuc assignment to a, and then evaluates the ACDD assignment to e; this is the simplest comma expression, and you can continue to add "," after ACDD.
Thank you for reading! This is the end of the article on "how to use question mark expressions in C language". I hope the above content can be of some help to you, so that you can learn more knowledge. If you think the article is good, you can share it for more people to see!