It has been a popular question about how to print hello world without using semicolon. I know many codes but this one sounds weird because I am unable to get the logic behind it. Please help me know how it prints.
if(printf("hello world")){}
It has been a popular question about how to print hello world without using semicolon. I know many codes but this one sounds weird because I am unable to get the logic behind it. Please help me know how it prints.
if(printf("hello world")){}
The bit about the semicolons is just a little "I'm smarter than you" misdirection.
However, when you get this you'll know something about c;
Here is a series of programs that may help. Compile and run each one, then think about what they do and how they differ from the ones that came before:
Finally, you are allowed to omit the return from main (which implicitly returns 0 in that case). So you get:
which is a complete, standard compliant version of Hello, world! without any semicolons.
printf() is a normal function that returns the numbers printed, so basically the code first calls printf() and then checks, whether its return values evaluates to true (i.e. more than 0 characters where outputted). This is the case for "hello world", however it does not matter, since the conditional block is empty anyway.
The
if
statement will simply check if the expression has evaluated to non-zero value. Soif (printf("Hello World")) { }
is pretty much the same is
if (printf("Hello World") != 0) { }
which
printf
needs to be called to evaluate the expression.You have to put a semicolon anyhow, just after the if statement, or you have to put an empty block after it.or
EDIT: I was sure that in the question there wasn't the empty block... I must have read it wrong, or it has been ninja-edited.
It works because printf is a normal function, returning the number of characters printed (as you can clearly see from its documentation); the if statement obviously evaluates the expression, thus calling the function (which incidentally prints the string on the screen).
Since the return type of printf is a number, and all the numbers are true which are not 0 and 0 is false, a number in an if statement can be evaluated. That's why the source code works. When you call a function in an evaluation the function must return the value before the evaluation happens, so printf does what it has to do, returns a number and the if evaluates it. That's what this source code does.
Take a look at the docs:
Return Value
On success, the total number of characters written is returned. On failure, a negative number is returned.
So it returns
1211 in the Hello World case and that number is interpreted as true value. Value of if test needs to be calculated to decide which code block to execute which means that printf() is called in the first place.