Palak Jain
Palak Jain

Reputation: 683

Why does printf() work even without being caught in an integer variable?

I was wondering if printf() in C or C++ programming language returns the number of characters printed on screen, then how does

printf("%d", 10); 

work? Why doesn't it show any error(s)?

Rather an integer variable should be used to catch the returned value, as follows:

int var = printf("%d", 10); 

How does printf() work internally to resolve this?

Upvotes: 1

Views: 200

Answers (1)

melpomene
melpomene

Reputation: 85767

printf() does nothing special here. C doesn't require you to do anything with the result of expressions you evaluate.

2 + 3;

is a perfectly valid statement. (It may generate a warning from your compiler because it doesn't actually do anything, unlike a function call such as printf().)

Let's look at a slight variation of your second version:

int var;
var = printf("%d", 10);

Here you might think we're "catching" the return value from printf in var, so there's no result value being left lying around. But = is just another operator (like + or &&) and it returns a value!

int x, y, z;
x = (y = (z = 42));  // perfectly valid code
x = y = z = 42;  // same thing; = is right associative

= returns the value being assigned and this code sets all three variables to 42.

So if C were to require you to "catch" return values, you couldn't use assignment statements because they also return a value.

Upvotes: 9

Related Questions