Megha M
Megha M

Reputation: 105

Why printf("test"); does not give any error?

If int x=printf("test"); executes safely, without error in because printf returns an int value (the length of data it has printed.) But what about if we are not storing that integer value:

printf("text"); 

Why don't we get an error from this?

Upvotes: 3

Views: 61

Answers (2)

John Burger
John Burger

Reputation: 3672

Many functions in C return something. Whether the programmer decides to do anything with that value is up to them - and often ignoring the return code leads to bugs... But in the case of printf(), the return value is seldom useful. It is provided for to allow the following code:

int width;

width = printf("%d", value); // Find out how wide it was
while (width++<15) printf(" ");
width = printf("%s", name);
while (width++<30) printf(" ");

I'm not saying that's good code (there are other ways to do this too!), but it describes why a function could return a value that isn't used very often.

If the programmer does decide to ignore the return value, there isn't a compiler error - the value is merely forgotten. It's a bit like buying something, getting the receipt, and dropping it on the floor - ignore the returned value.

The latest compilers can be instructed to flag code where returned values are ignored. But even these compilers can be taught which functions' returns are significant and which aren't. printf() would be in the second category.

Upvotes: 1

Kelm
Kelm

Reputation: 968

You are not obliged to store the returned value, you can safely ignore it (as long as you're sure you really don't need it of course).

In most cases the value is simply stored in a CPU register. If you choose to ignore it, it will simply be lost once that register is overwritten.

Upvotes: 0

Related Questions