When using the scanf function, we cannot simply specify the variable name. Rather, we have to prefix the variable name with an ampersand, e.g. int a; printf("enter your value"); scanf("%d", &a);.
I checked online sources searching for the reason. Most of them say something like:
We need to modify the value in that variable. We add
&to denote a memory location, so that the value at that location can be changed.The arguments to the
scanf()function have pointer type: it needs to be given a memory address, so that it can change the variable’s value.
I am new to coding, so I am little bit confused about this. If we need the address to modify what the memory contains, why do we not use & when assigning to a variable, e.g. int a; a = 5;? In this example, we also we modify the value. Why do we not write it like this: int a; &a = 5;?
Because you want
scanf()to take in input, and write that data to the memory location of the variable you need the data to be in.&means you are passing the memory address of that variable.So:
Why do you have to pass the address? Because you want scanf to write at the memory address of (x), not at the memory address (x).
Doing this will result in undefined behaviour:
Fun fact:
NULLis C is usually defined as(void *)0. So the above is equivalent toscanf("%d", NULL);=is an operator, not a function call, so it already knows the memory address of the variable. So it doesn't need the&.