0
In scanf() fn, we use & ("adress of" operator) before a variable... Then why & is not used before a variable in printf() fn in C
& is used in scanf() function so that the scanf() may get the address of the variable to store the input from user (value of variable) at that location. Why scanf() cannot access the variable just by knowing the variable name...? As the printf() can access the variable (value of the variable) by just knowing the variable name.
2 Réponses
+ 4
Because printf does not need the address of the variable. It just outputs the value on the screen.
But scanf needs to change the actual variable, that's why you needd the address
+ 4
In C, everything is passed by value.
If you do not pass the address of a variable to scanf, and just pass the variable itself, any changes made to the value of the scanf arguments will not be reflected in the variables. Compare:
void changeValue1(int n) {
n = 39;
}
void changeValue2(int* n) {
*n = 39;
}
int main() {
int n = 0;
changeValue1(n);
printf("%d\n", n);
changeValue2(&n);
printf("%d\n", n);
}