printf("%d") doesn't display what I input

printf("%d is what I entered\n", &number);

is wrong because %d(in the printf) expects an argument of type int, not int*. This invokes Undefined Behavior as seen in the draft (n1570) of the C11 standard (emphasis mine):

7.21.6.1 The fprintf function

[...]

  1. If a conversion specification is invalid, the behavior is undefined. 282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Fix it by using

printf("%d is what I entered\n", number);

Then, Why does scanf require & before the variable name?

Keep in mind that when you use number, you pass the value of the variable number and when you use &number, you pass the address of number(& is the address-of operator).

So, scanf does not need to know the value of number. It needs the address of it (an int* in this case) in order to write the input into it.

printf, on the other hand, does not require the address. It just needs to know the value (int, in this case) to be printed. This is why you don't use & before the variable name in printf.


You're using operator& on number, means take address of it, so you're not printing the value of number, but the address of it, you should:

printf("%d is what I entered\n", number);

If you would have used -Wall -g compiler option, then you should have seen the error right during compile time:

# cc -Wall -g ex.c -o ex
ex.c: In function ‘main’:
ex.c:9:10: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
   printf("%d is what I entered\n", &number);
      ^

Tags:

C

Printf