0
Hello, Everyone! I'm new to C programming.Can anyone please explain me what happens near if statement in the code below?
#include<stdio.h> int main() { if(printf("Hello, C Programmer!")) { } }
6 ответов
+ 4
printf() function returns number of charecters successfully printed.You can verify this by trying this code :
int n = printf("Hello");
printf("%d",n); //5
If you convert any non-zero number to boolean value it'll be `true`. If number is 0 then it's treated as `false`.
In given code printf() function returns integer value 20 , which is non-zero.
So code enclosed within if statement will be executed.
+ 4
It will output
Hello, C Programmer!
Using if like this is a common trick in several C syntax style languages to write a program without using a semicolon.
It can also be a way to run the code within the if block if printf has successfully written any characters. As 🇮🇳Omkar🕉 has stated any non-zero value will result in true. However, it returns 20 not 21. printf() returns the count of characters written.
+ 2
ChaoticDawg ,
Thanks for correction. I edited my answer.
Tried counting many time but poor eyesight , lol 👀.
+ 2
Thanks a lot 🇮🇳Omkar🕉 ChaoticDawg for clarifying my doubt.
0
Thanks Akash_Kumar