繁体   English   中英

if 条件中的 printf 语句

[英]printf statement inside the if condition

谁能解释一下这是如何工作的,输出是 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以外的0被视为真,因此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

也就是说,如果不需要转换规范,则不应使用printf() ,而应使用puts()fputs()

笔记:

printf()

返回值成功返回后,这些函数返回打印的字符数(不包括用于结束输出到字符串的空字节)。

理解这种行为的技巧就在这里和返回值 od 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

暂无
暂无

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

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