43. Increment Value Pointer vs Reference

#include <iostream>
using namespace std;

void incrementPtr(int* x) {
    (*x)++;
}

void incrementRef(int& x) {
    x++;
}

int main() {
    int n;
    cin >> n;

    int a = n;
    incrementPtr(&a);
    cout << "After incrementPtr: " << a << "\n";

    int b = n;
    incrementRef(b);
    cout << "After incrementRef: " << b;

    return 0;
}

Solution Details

  • incrementPtr(int* x) → uses a pointer, so we must dereference with *x to access and change the value.
     
  • incrementRef(int& x) → uses a reference, which is just an alias for the original variable, so x++ changes the caller’s variable directly.
     
  • Both modify the original variable, but references are safer and simpler.

     

👉 In simple words:

  • Pointer: “Give me your address, I’ll go there and change it.”
  • Reference: “I’ll just use your nickname and change you directly.”
     

Significance for Embedded Developers

  • Many embedded APIs still use pointers (C-style).
     
  • C++ allows references, which provide the same effect with less error risk.
     
  • Useful for manipulating registers, counters, and flags directly inside functions.
     
Loading...

Input

5

Expected Output

After incrementPtr: 6 After incrementRef: 6