I recently heard this was used as an interview question. I suspect there is a very simple answer; I must be over-thinking it.
Can you write Hello World in C without using any semi-colons? If so, how?
I recently heard this was used as an interview question. I suspect there is a very simple answer; I must be over-thinking it.
Can you write Hello World in C without using any semi-colons? If so, how?
#include<stdio.h>
main()
{
if(printf("Hello World \n"))
{
}
}
Any ANSI C solution with printf
would require #include <stdio.h>
or an explicit "manual" declaration of printf
to be correct (the latter would need a semicolon though), since without the declaration of printf
the behavior of the program is undefined.
One can also argue that by doing #include <stdio.h>
you are implicitly introducing semicolons into your code :)
If you care to make it more compact, and also discourage any potential #include <stdio.h>
protesters, use puts
instead of printf
main() {
if (puts("Hello World")) {}
}
Of course, this is only valid in C89/90.
int
main (void)
{
while (puts ("Hello World!") && 0)
{}
}
Unfortunately, that omits the return statement. Some compilers will issue a warning, but it will still compile. The only one that REALLY works and is completely valid at the time of this writing (despite not producing a binary and lacking a main
function in some form) is the one using #error "Hello World"
. Of course, that's if you're shooting for full C89/C90 compatibility with C99 as well. :P
And here's a semicolonless quine, inspired by this question:
#include <stdio.h>
main(char* a){if(a="#include <stdio.h>%cmain(char* a){if(a=%c%s%c){if(printf(a,10,34,a,34)){}}}"){if(printf(a,10,34,a,34)){}}}
Compile with gcc.
To be compliant, it should return a status code of 0 to the OS.
I like this version:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
if (printf("Hello World\n"), exit(0), 0) { }
}
(answer edited based on comments. Tested under VS 2010 as Win32 Console App)
file name:
void main(){if(puts("Hello, World!")){}}
file contents:
A
compile with:
-istdio.h -DA=__FILE__
Can you write Hello World in C without using any semi-colons? If so, how?
Sought out answer already provided, but given the question...
[sarcasm]
int main()
{
// Hello World
}
[/sarcasm]
I think a lot of interview questions are often very poorly worded. I was once asked, "How many bits are required to represent the number, 32?" I had to ask, "for what range, and is this for integers only?" The interviewer answered that it was for integers and starting from zero, so I said 6. Then he said that was wrong and the correct answer was 5. I told him he was wrong as that would assume the range [1, 32], not [0, 32] which would have 33 unique values and would require 6 bits. I got the job but the interview was silly. Sometimes it seems like they just came up with the question on the spot.