So I'm trying to understand passage by reference and I came across this code:
#include <iostream>
using namespace std;
int main() {
int var;
int *ptr;
int val;
var = 3000;
// take the address of var
ptr = &var;
// take the value available at ptr
val = *ptr;
cout << "Value of var :" << var << endl;
cout << "Value of ptr :" << ptr << endl;
cout << "Value of val :" << val << endl;
return 0;
}
The thing about the code is that I don't understand why we have to do ptr = &var
. Since ptr is a pointer, shouldn't it already be pointing to the address of var? And also, what would happen if I just type ptr = var
instead?