printf() function inside control statements such as
if, switch, or while.
Method 1: Using an if Statement
Since if is a control statement and does not require a semicolon
after its condition, we can place printf() inside it.
#include
int main()
{
if (printf("Hello World"))
{
}
return 0;
}
Output
Hello World
Method 2: Using a switch Statement
#include
int main()
{
switch (printf("Hello World"))
{
}
return 0;
}
Output
Hello World
Method 3: Using a while Loop
The printf() function returns the number of characters printed.
Since the returned value is non-zero, the loop condition becomes true. The
break statement is then used to exit the loop immediately.
#include
int main()
{
while (printf("Hello World"))
{
break;
}
return 0;
}
Output
Hello World
Why Does This Work?
The printf() function does more than just display text. It also
returns the number of characters printed.
Since 11 is a non-zero value, it is treated as
true in C. Therefore, control statements like
if, while, and switch execute successfully.
Comparison of Different Methods
| Method | Uses Semicolon After printf()? |
Recommended? |
|---|---|---|
if (printf()) |
No | Yes (Interview Purpose) |
switch (printf()) |
No | Yes (Interview Purpose) |
while (printf()) |
No | Yes (Interview Purpose) |
Normal printf(); |
Yes | Recommended for Production Code |
Important Note
Don't Use in Production
- Reduces code readability.
- Can confuse beginners.
- Not considered a coding best practice.
- Mainly asked in C programming interviews.
Best Practice
- Use the normal
printf("Hello World");syntax. - Learn these tricks for interviews and competitive programming.
- Write clean and maintainable code in real projects.
Prerequisites
Before Learning This Topic
- Basic knowledge of C program structure.
- Understanding of
printf(). - Knowledge of control statements (
if,while, andswitch). - Basic understanding of return values in C.
Interview Questions
- What value does
printf()return? - Why does
if(printf("Hello World"))execute successfully? - Can we print text without writing a semicolon in C?
- Is this technique recommended in production code? Why?
- What happens if
printf()returns 0?
Key Takeaway
It is possible to print "Hello World" without explicitly
writing a semicolon after printf() by placing it inside control
statements like if, switch, or
while. This works because printf() returns the
number of characters printed, which is treated as true in C.
These techniques are popular interview questions but should not replace
standard coding practices in real-world applications.