Reputation: 1949
My Code:
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
Upvotes: 0
Views: 1480
Reputation: 58271
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.
Upvotes: 3
Reputation: 27792
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.
Upvotes: 5
Reputation: 223
"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 .
Upvotes: -1
Reputation: 2384
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.
Upvotes: 1