Is there any method to use a conditional statement inside other statements, for example printf
?
One way is using ternary operator ? :
? :
eg:
printf("%d", a < b ? a : b);
Is there a method for more complicated conditions?
There is no need for more complex expressions, the conditional operator is already bad enough. There is no language feature for it. Instead, write a function.
printf("%d", compare(a,b)); // good programming, readable code
printf("%d", a<b?(x<y?x:y):(x<y?y:x)); // bad programming, unreadable mess
You cannot put statements into printf
at all, you only can put expressions there. The ternary operator forms an expression . An expression is basically a tree of operators and operands, however there are a few funny operators allowed, like the ',' comma operator or the '=' assignment operator. This allows expressions to have side effects.
Every conditional statement return 1
or 0
. These values are int
So if you do printf("%d",a>b);
then either 1
(true) or 0
(false) will be printed.
In your example you are using ternary operator a<b?a:b
. If condition is true then a
will be printed else b
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.