Pointers and References (Part 1: Declaring and assigning value)





Note: This post assumes you know the basics of programming and programming language C/C++. This blog is for those who want to learn how variables are stored, how pointers and references work, when and why to use them.

Let's start with what happens when you declare a variable. Like this,

 int a = 0;

When you run this, '0' will be stored in memory and 'a' will be nowhere in your final compiled program. But for programmer's sake (so that we won't lose minds) we have a variable name till we compile the code. We will talk more about what happens after compilation later.

Tip: Here 'int a' is declaration part and '= 0' is assignment part (important for upcoming tips). 

We will call 'a' as a label for that memory location. Let say '0' gets stored in RAM at place 0x00001234.



Reference:

Now, let's move on to what is a reference. It is just one more label for the same memory location. We will declare a reference b,

 int &b = a;



Tip: Whenever we use '&' in declaration part, read '&' as a reference not address (because it isn't).

Now 'a' and 'b' refer to the same memory location.

There are some rules for declaring a reference. A reference must be initialized to a variable of the same type because it is just a label, it can not exists on its own (why and more on this at the end).

You can use reference for any (valid) operations same as you would use a variable. In our example, you can do

 b = 10;





b = b + 10;

                           


// or even this
a = b + 10;

                         

Pointer:

Let's move on to the pointer. A pointer is variable which stores address of another variable. We can declare one by using '*'. Let's declare a pointer 'c',

 int *c;

Tip: Whenever we use '*' in declaration part, read '*' as 'pointer'.  

                         

'c' will have garbage value in it. We assumed garbage value was 0x00000000. 'c' being a variable get's its own place in memory and an address. We assumed here it to 0x00002345.

As you might have noted, we did not initialize the pointer. As it is a variable it can exist on its own (because it has memory allocated to it).

We can initialize it store an address of 'int' variable.

 c = &a;

                         

  Tip: Whenever you use '&' in assignment part, read '&' as 'address of'.

 We can use 'c' to assign values for variable 'a'. *c = 40;
                       
  Tip: Whenever you use '*' in anywhere except declaration, read '*' as 'value at'.  

Comments

Popular posts from this blog

Pointers and References (Part 2: When and How to use them)