Why does scanf require &?
I want to read a number from stdin. I don't understand why scanf
requires the use of &
before the name of my variable:
int i;
scanf("%d", &i);
Why does scanf
need the address of the variable?
It needs to change the variable. Since all arguments in C are passed by value you need to pass a pointer if you want a function to be able to change a parameter.
Here's a super-simple example showing it:
void nochange(int var) {
// Here, var is a copy of the original number. &var != &value
var = 1337;
}
void change(int *var) {
// Here, var is a pointer to the original number. var == &value
// Writing to `*var` modifies the variable the pointer points to
*var = 1337;
}
int main() {
int value = 42;
nochange(value);
change(&value);
return 0;
}
C function parameters are always "pass-by-value", which means that the function scanf
only sees a copy of the current value of whatever you specify as the argument expression.
In this case &i
is a pointer value that refers to the variable i
. scanf
can use this to modify i
. If you passed i
, then it would only see an uninitialized value, which (a) is UB, (b) is not sufficient information for scanf
to know how to modify i
.
It's not needed.
char s[1234];
scanf("%s", s);
Works just fine without a single &
anywhere. What scanf
and company need are pointers. To let it modify a particular variable, you pass the address of that variable. For a few types that happens by default. For others, you use &
to take the address (get a pointer to that variable).
Because otherwise it would only be altering a copy rather than the original.