简体   繁体   English

`printf`里面的条件语句

[英]Conditional statements inside `printf`

Is there any method to use a conditional statement inside other statements, for example printf ? 是否有任何方法在其他语句中使用条件语句,例如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. 你根本不能把语句放到printf中,你只能把表达式放在那里。 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 . 每个条件语句都返回10 These values are int 这些值是int

So if you do printf("%d",a>b); 所以如果你做printf("%d",a>b); then either 1 (true) or 0 (false) will be printed. 然后将打印1 (真)或0 (假)。

In your example you are using ternary operator a<b?a:b . 在您的示例中,您使用的是三元运算符a<b?a:b If condition is true then a will be printed else b . 如果条件为真,那么a将要打印的其他b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM