what happens if I use a pointer and dont use the "&" symbol

Viewed 99

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?

2 Answers

In your code, int *ptr; doesn't store the address of anything at first. So if you tried to dereference the pointer without setting it to &var, your code will have undefined behavior. It might crash; it might output some garbage number, who knows...

By writing ptr = &var, you are telling c++ to set the ptr variable to the address of var. Once you've done this, now c++ is actually pointing to an integer variable and can be dereferenced with defined behavior. If you change var = 12, dereferencing ptr will result in 12.

If you typed ptr=var, you are telling c++ to set the ptr variable to the value of var which doesn't make sense. The compiler knows this and will spit out an error error: invalid conversion from ‘int’ to ‘int*’

Since ptr is a pointer, shouldn't it already be pointing to the address of var?

No, just because ptr is a pointer it will not be autmatically pointing to var. Imagine if you many int variables like var then how will the compiler know which one to point to.

Also, if you write int *ptr; then the pointer ptr is uninitialized meaning it has indeterminate value. If you were to now dereference this uninitialized pointer then the program will have undefined behavior.


what would happen if I just type ptr = var instead?

You can't because it is illegal to assign an int variable to a pointer, even if the variable’s value happens to be 0. But note that you can use the integer literal 0 to initialize ptr. This is because 0 is also a null pointer constant that converts to any pointer type.

int *ptr; //ptr is uninitialized and if you were to dereference ptr, it will be undefined behavior
ptr = 0;  //VALID because 0 is a null pointer constant 

int var = 0;
ptr = var;  //INVALID
Related