Skip to main content

Why we are not use “&” with cin in C++ language but use with scanf() in C language?


Why we are not use “&” with cin in C++ but use with scanf() in C?

by Ayush garg

Prerequisite for batter understanding –

1. basic in knowledge of polymorphism a concept of object oriented programming .
2.Basic knowledge of function 
.
When C programmer start studying C++ one doubt always ring in his mind why “&” not used with cin in C++ but use with in scanf() in C?

In C++ program write as

int a;
cin>>a;

C++ is the object oriented programming language and  cin is an object. Here concept of operator overloading is used. In C “>>” is called right shift bitwise operator. Here “>>” is overloaded.

 When object file create 
cin>>a;
 Is internally converted into
cin.operator>>(a)

It means it is a function call. cin.operator>>(a) is function call so its definition must be present somewhere in class form which cin object belong.
In C++ there are three type of function call:-
1.Call by value.
 2.Call by reference.
3.Call by address.

1.    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.

2.    Call by reference- in call by reference the reference of the variable is pass.  Here reference means another name of the variable. By using call by reference we are able to make change in the actual argument.

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

Here in call by reference is used. Reference variable is written as
int &y=x;
It is alias name (another name) of the variable so the reference of a variable as an argument is passed and by passing the reference the variable easily access form the function definition.
function definition have some kind of code because of which we are able to the value form standard input device keyboard and that indirectly stored in the variable with is pass .

Why call by value is not use?

Call by value is not use because by using it programmer is able to pass multiple values at a time but only single value return. If call by value programmer have to use cin multiple for the multiple variable which make source code lengthy and  also make program slow.

Why call by address is not use?

Call by address is not use because by using it programmer always have to use cin>>&x instead of cin>>x and if programmer forget “&” with variable program may be crash and display unexpected output. To prevent form that kind of mistake and make input statement more flexible call by reference is used.

                
                     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