C / C++ FAQs & Programming Resources - ProkutFAQ : PrintfWithoutSemicolon

HomePage Recent Changes Recently Commented Login/Register

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.


CategoryPuzzles
 Comments [Hide comments/form]
I feel the second statement is wrong...
dont you think the prog will execute an infinite loop printing hello world???
-- 203.110.243.21 (2006-10-18 02:32:49)
Thanks for pointing that out. It would work fine now.
-- PriyaSridharan (2006-10-20 02:14:12)
I think 2 nd statement will be use ful if we want to Explain importance of a break statement in a program
-- 220.227.56.19 (2006-12-08 04:13:09)
I think 3 rd statement is true.
-- segment-124-7.sify.net (2007-01-13 09:02:37)
I think I've only one word to express my feelings

Awesome
-- 217.73.15.6 (2007-03-07 06:01:52)
that's gr8
-- 202.53.8.200 (2007-03-16 06:35:34)
good, better, best!!
-- 59.92.32.123 (2007-05-14 05:52:50)
nice thinking !!
-- 59.93.78.146 (2007-06-03 02:02:59)
very useful
-- ABTS-NCR-Dynamic-203.115.162.122.airtelbroadband.in (2007-06-11 06:56:49)
oh tat's really a gud qutn.... & 1st ans's realy gud
-- 203.153.35.72 (2007-12-22 05:54:24)
Page was generated in 0.1091 seconds