1

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?

Palak Jain
  • 664
  • 6
  • 19
  • 1
    What error are you expecting? You don't have to assign or use the return value of a function. – Igal S. Apr 24 '18 at 06:38
  • 2
    You don't mention the programming language, but I don't know of any where you *must* store the return values of functions somewhere. Why do you think otherwise? – JJJ Apr 24 '18 at 06:38
  • 1
    If this is your question, yes `int printf()` returns the number of written characters if you are on C/C++, and a negative number on error. See [here](https://stackoverflow.com/a/7055895/7477557). To catch errors you can simply do `if( printf(...) < 0 ) manageerror(); ` Note that it does not output the number of items but characters (newline is 1, any byte is 1) – xdrm Apr 24 '18 at 06:42
  • 2
    *"How does `printf()` work internally to resolve this?"* -- `printf()` (or any other function that returns a value) doesn't care what happens with the value it returns. It always returns it and completes; it's up to the calling code to use or ignore the returned value. `C` and other languages inspired from it allow calling a function without using the value it returns. – axiac Apr 24 '18 at 06:42
  • If you start out life programming in VBA (where with some syntaxes and functions you *do* need to do something with the return value), this is not immediately obvious. Upped. – Bathsheba Apr 24 '18 at 07:05
  • I used to think that it's compulsory to use the returned value of a function. But thankfully, today my misconception is cleared @IgalS. – Palak Jain Apr 24 '18 at 07:13

1 Answers1

9

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.

melpomene
  • 84,125
  • 8
  • 85
  • 148