Friday, January 6, 2012

Printing "Hello World" to screen without using a single semicolon in C/C++

When I first encountered this question, I thought it was impossible. However, there are ways to do so. I don't know if the solutions are exploitation of c / c++. Anyway, here are the most common solutions:
int main()
{
    if (printf("Hello World \n")) { }
}



Or you can use the while loop like this:
int main()
{
    while (printf("Hello World") > 20) { }
}
If you don't think these codes will work, try them out. They are weird but work well in c / c++.
Notice: These don't work in Java. Not sure about other languages, so use them responsibly. After all, this is just for fun :)

2 comments:

  1. yes.it works fine.bt would you plz explain how?

    ReplyDelete
    Replies
    1. Its because printf() returns the characters it prints. So if we do printf ("Hello World\n") ... it returns 10 (for helloworld) + 1 (for space) + 1 (for \n)=12.
      Now, coming to main part, if(12) , will be executed as in C language, if(0) is like if (false), but if(any other integer) is true, so if statement is executed, meanwhile printing Hello World. Here is more info:
      stackoverflow for printf()

      Delete