Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If int x=printf("test"); executes safely, without error in c 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?

like image 221
Megha M Avatar asked Jan 21 '26 19:01

Megha M


1 Answers

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.

like image 130
John Burger Avatar answered Jan 24 '26 09:01

John Burger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!