0

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

Xiddoc
  • 3,369
  • 3
  • 11
  • 37
user1762571
  • 1,888
  • 7
  • 28
  • 47

4 Answers4

5

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.

jh314
  • 27,144
  • 16
  • 62
  • 82
3

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.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
1

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.

MasterHD
  • 2,264
  • 1
  • 32
  • 41
-1

"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 .

Rainer Liao
  • 223
  • 3
  • 13