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.

25th Aug 2019, 6:35 AM
Vandana
Vandana - avatar
2 ответов
+ 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
25th Aug 2019, 6:42 AM
Airree
Airree - avatar
+ 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); }
25th Aug 2019, 6:45 AM
Hatsy Rei
Hatsy Rei - avatar