DEV Community

Suman Samanta
Suman Samanta

Posted on

Day 4 of #100DaysOfCode

Today I Learned (Pointers in C++)

  • Understood memory concepts: how variables are stored in RAM
  • Learned about the address-of operator (&) and how to use pointers (*)
  • Explored dereferencing, null pointers, and their use cases
  • Differentiated pass-by-value vs pass-by-reference
  • Practiced with reference variables and how they differ from pointers
#include <iostream>
using namespace std;

void passByValue(int x) {
    x = x + 10;
}

void passByReference(int &x) {
    x = x + 10;
}

int main() {
    int a = 5;
    int* ptr = &a;  // pointer to a
    int* nullPtr = nullptr;  // null pointer

    cout << "Address of a: " << &a << endl;
    cout << "Value of ptr: " << ptr << endl;
    cout << "Value pointed by ptr: " << *ptr << endl;

    int val = 100;
    passByValue(val);
    cout << "After passByValue: " << val << endl;

    passByReference(val);
    cout << "After passByReference: " << val << endl;

    int &ref = a;
    ref += 20;
    cout << "\nReference variable updated a to: " << a << endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Takeaway

Pointers are powerful tools for understanding how memory works.

Codes: https://github.com/GeekyProgrammer07/DSA

Top comments (0)