Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf statement inside the if condition

Tags:

c

printf

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);
}
like image 340
Nirosh Avatar asked Jan 25 '26 23:01

Nirosh


1 Answers

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.

like image 169
MikeCAT Avatar answered Jan 28 '26 16:01

MikeCAT