Conditional statements inside `printf`
Solution 1
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
Solution 2
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.
Solution 3
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
.
Nitin Labhishetty
Updated on July 17, 2022Comments
-
Nitin Labhishetty almost 2 years
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?
-
Michael over 7 yearsTernary operators are pretty normal and when used well make code quite readable and more compact. On the other hand, having to jump through more methods can make debugging complex systems that much more difficult. If its a simple if / else type of comparison, go at it and use a ternary, if its nested with complex logic, then sure, use a method.
-
Lundin over 7 years@Michael Common sense has to be applied from case to case. There are indeed some cases where the
?:
operator makes code more readable (like switch statements where the only task of eachcase
is to assign a value based on a condition), but in the majority of the cases, such as in this example, it actually tends to make code less readable. Therefore, it is an operator to use with care - always consider if other solutions are more readable. Also, unlikeif
statments, the?:
invokes multiple implicit type promotions, which can cause unexpected problems.