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?

6
  • 1
    What error are you expecting? You don't have to assign or use the return value of a function. Commented Apr 24, 2018 at 6: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? Commented Apr 24, 2018 at 6: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. 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) Commented Apr 24, 2018 at 6: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. Commented Apr 24, 2018 at 6: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. Commented Apr 24, 2018 at 7:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.