[英]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);
}
讓我們檢查一下流程:
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()
。
筆記:
返回值成功返回后,這些函數返回打印的字符數(不包括用於結束輸出到字符串的空字節)。
理解這種行為的技巧就在這里和返回值 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.