Вопрос

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top