簡體   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