简体   繁体   中英

printf statement inside the if condition

Can anyone explain how does this work the output is A3 but how come it print 3

#include <stdio.h>

int main() {
    int i;
    if(printf("A"))
        i=3;
    else
        i=5;
    printf("%d",i);
}

printf() returns the number of characters upon success and negative values on failure.

Therefore, if printf("A") succeeds, it will return 1 .

In C, values other than 0 is treated as true, so i=3; is executed.

Let's check the flow:

    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.

Final print is A3 .

That said, if no conversion specification is needed, instead of using printf() , one should use puts() or fputs() .

Note:

From man printf()

Return value Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).

the trick to understand this behav is here and the return val od printf

returns the number of characters upon success and negative values on failure. this here:

if(printf("A"))

can be read as

int r = printf("A");// at this point r ==1

if(1) //this here is true so i is assigned to 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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