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
  • 1,810
  • 3
  • 6
  • 23
user1762571
  • 1,758
  • 5
  • 24
  • 45

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
  • 25,902
  • 15
  • 60
  • 80
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
  • 55,177
  • 19
  • 133
  • 197
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,028
  • 1
  • 29
  • 39
-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