Skip to main content

Why “&” used with scanf() in C language?


Why “&” used with scanf() in C?

                                                    -by Ayush garg

Prerequisite for the batter understanding-
1. Basic knowledge of the pointer.
2. Basic knowledge of the function.

When beginner start studying C one doubt always in his mind. Why “&” is used with scanf() in C.

In C “&” called address of operator. When  “&” used with variable it always return the address of that variable and we know that when any variable declare in the program and when program run a memory allocated to it in  RAM. This allocated memory always has some address.
In C we have two type of function call:-
1.    Call by value.
2.    Call by reference.

Call by value- In call by value the value inside the variable is passed. By using call by value we are not able to make any change in the actual argument.

Call by reference- In call by reference by using “&”the address of the variable is passed. By using call by reference we are able to made changes in the actual argument. In call by reference the argument are receive by the pointer variable.

C also has the concept of pointer. Pointer is the variable which is is able to store the address the address of another variable.
  Ex.
Int  a;
int *ptr=&a;

Here ptr are the pointer variable and store the address of a.
When we write

Int x;
sacnf(“%d”,&x);

Here call by reference is used. Above function scanf() is call to the function and here by using “&” we are passing the address of variable.

This address is receive by the definition of scanf() which contain the pointer variable as an argument . scanf() is predefined function whose deceleration is inside the header file and definition inside the library file.

Inside the definition of the scanf() some kind of coding present by which we are able to input any through standard input device.

Why call by value is not used?

In scanf() call by reference is used not call by value because each when we call function sancf() we are able to pass multiple variable at a time but able to return only single value.

Because of that we have to call scanf() multiple times for multiple variables and it consume time (function call and value return consume time) and our program become slow. That why we use call by reference by passing a reference we are able to make change in the actual argument so there is no need of return statement. And we are able pass multiple variable in single call.   

Thank you. 
If you have any suggestion for improvement or found mistake or if you like please writer in comment in the comment section and share it.




Comments