如何解决if条件中的printf语句
任何人都可以解释输出A3但它如何打印3的工作原理
#include <stdio.h>
int main() {
int i;
if(printf("A"))
i=3;
else
i=5;
printf("%d",i);
}
解决方法
printf()
返回成功时的字符数,失败时返回负数。
因此,如果printf("A")
成功,它将返回1
。
在C中,将0
以外的其他值视为true,因此执行i=3;
。
让我们检查一下流程:
int i; --> i has indeterminate value
if(printf("A")) --> prints A and returns 1,so the condition is TRUE (see note)
i=3; --> This statement is executed
else --> this condition is skipped
i=5; --> so this does not execute
printf("%d",i); --> prints the value of i which is 3.
最终打印为A3
。
也就是说,如果不需要转换规范,则应该使用puts()
or fputs()
而不是printf()
。
注意:
,返回值 成功返回后,这些函数将返回打印的字符数(不包括用于结束输出到字符串的空字节)。
了解这种行为的技巧是here和返回值printf
成功时返回字符数,失败时返回负数。 在这里:
if(printf("A"))
可以读为
int r = printf("A");// at this point r ==1
if(1) //this here is true so i is assigned to 3
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。