Posts

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

Image
Note: This post assumes you know the basics of programming, programming language C/C++ and read Part 1: Declaring and assigning value. This blog is for those who want to learn how variables are stored, how pointers and references work, when and why to use them. We use a function in our code to make it modular and intuitive. To understand how parameters in function are stored in memory, let's start with how a function call works through the following example. void print(int a) { cout << a; } int main() { int a = 10; print(a); return 0; } In memory, there is a call stack to keep track of active/running function calls in a program. When we start our program, stack frame for main is loaded in the call stack.   When execution reaches to function call to 'print' function. Then stack frame for 'print' function is loaded in to call stack as well. The interesting thing happening here is, 'print' function has it's own v...

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

Image
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 refere...