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.

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.

 Comments [Hide comments/form]
I feel the second statement is wrong...
dont you think the prog will execute an infinite loop printing hello world???
-- (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
-- (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

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