Lets look at your code:
#include <stdio.h>
int main (int argc, const char * argv[]) {
char out = printf("teststring");
printf("%d\n", out);
return 0;
}
And change it:
#include <stdio.h>
int main (int argc, const char * argv[]) {
const char *str = "teststring";
int out = printf("%s", str);
printf("\nPrintf wrote %d bytes when printing %s\n", out, str);
return 0;
}
Compile / run the edited version and you should immediately see the difference. Modify the length of str
then compile and run it again.
Now, just a tiny change to your original code:
#include <stdio.h>
int main (int argc, const char * argv[]) {
char out = printf("teststring\n");
printf("%d\n", out);
return 0;
}
You can see now, you are printing two different things, and out
has become 11, since a newline was added. Nothing is actually trailing here. Then change %d
to %c
(the correct format specifier for out
in your example) and notice the difference. ASCII (11) is a vertical tab (see here). YTMV (your terminal may vary). Here, you printed a character, not a character representation of an integer.
The actual type that printf()
returns is int
, which is an integer. The reason for this is so that you know exactly how many bytes printf()
actually printed. This typical for that family of functions, but more useful for functions like snprintf()
so you can know if it could not print the entire length of any given format to a buffer. Note that the return type is signed, it can be negative, so the storage type you pick to store its value matters quite a bit, especially if you work with that value while assuming that its greater than or equal to zero.
Here is a handy tutorial to format specifiers you can use with the printf()
family of functions. More importantly, check the return type of the functions that you are using.
I also suggest spending some quality time with this book, be sure to work through the exercises as time permits. Its the best self-study course in C and the exercises are fun. When you get a solid grasp of C, work through the exercises again .. then compare your answers, its eye opening :)