Thursday, August 28, 2008

How to printf "Hello World" without using a semicolon

How to use printf function without semicolon?



There are several ways to do this, below are some of the most popular ones:

  • if(printf("Hello, World!\n")) { }

  • while(!printf("Hello, World!\n")) { }

  • switch(printf("Hello, World!\n")) { }

This exercise has no particular use, but it keeps puzzling the newbies, and most of the companies in India happen to ask this question in interviews.
Explanation
The if, while and switch statements take a scalar type value as expression. Since printf function returns an integer (scalar type) value indicating the number of characters printed successfuly, it can be given as an expression to these statements and do away without the semicolon.

0 comments: