Hello, Everyone! I'm new to C programming.Can anyone please explain me what happens near if statement in the code below? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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!")) { } }

15th May 2020, 10:31 AM
__The__True__Villain__
__The__True__Villain__ - avatar
5 Answers
+ 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.
15th May 2020, 10:38 AM
๐Ÿ‡ฎ๐Ÿ‡ณOmkar๐Ÿ•‰
๐Ÿ‡ฎ๐Ÿ‡ณOmkar๐Ÿ•‰ - avatar
+ 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.
15th May 2020, 10:50 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
ChaoticDawg , Thanks for correction. I edited my answer. Tried counting many time but poor eyesight , lol ๐Ÿ‘€.
15th May 2020, 12:20 PM
๐Ÿ‡ฎ๐Ÿ‡ณOmkar๐Ÿ•‰
๐Ÿ‡ฎ๐Ÿ‡ณOmkar๐Ÿ•‰ - avatar
+ 2
Thanks a lot ๐Ÿ‡ฎ๐Ÿ‡ณOmkar๐Ÿ•‰ ChaoticDawg for clarifying my doubt.
15th May 2020, 1:25 PM
__The__True__Villain__
__The__True__Villain__ - avatar
0
16th May 2020, 1:29 AM
__The__True__Villain__
__The__True__Villain__ - avatar