int main()
{
int x = 10, y;
y = printf("x = %d\n", x);
printf("y = %d\n", y);
return 0;
}
output:
x = 10
y = 7
I know printf returns the number of character when we print string. But why is returning 7 when printing 10. what is the return value of printf when it prints int ?
Possible Duplicate: Return value of printf() function in C
Like you said, "printf returns the number of character when we print string".
" x = 10\\n
" has 7 chars. (Namely, these: 'x',' ','=',' ','1','0','\\n'
).
Thus, y is set to 7.
Read: int printf ( const char * format, ... );
On success, the total number of characters written is returned.
for x = 10
in your code first printf:
printf("x = %d\n", x);
prints seven chars x = 10\\n
, and return 7 that is received in y
:
x = 10\n
1234567
^ ^ ^- new line char \n
| |--spaces
remember \\n
(new line)is single char, and space is single char.
The length of the string:
"x = 10\n"
(not including double quotes) is 7 characters. That is what is being stored in y . The white spaces and '\\n' are also each just 1 character.
"x = %d\\n" Of course there are 7 characters. Notice there are 2 "space",1 "%" and 1"d", remember "\\n" is a whole . You can try other sentences. such as z = printf("x = %d,asd\\n",x);
or sth. like that. The answer is 11. I think such questions can be done by just one more line codes .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.