1. Pointer Reference Increment

#include <iostream>

void incrementPtr(int* x) {
    if (x != nullptr) {
        (*x)++;
    }
}

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

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

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

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

    return 0;
}

Solution Details

  • incrementPtr(int* x)
    • Uses a pointer to access the caller’s variable
    • Requires explicit dereferencing
    • Includes a null check to prevent undefined behavior
  • incrementRef(int& x)
    • Uses a reference as an alias to the original variable
    • Cannot be null
    • Allows direct modification without dereferencing
       

Significance for Embedded Developers

  • Pointer-based interfaces are common in:
    • C libraries
    • Hardware abstraction layers (HAL)
    • Memory-mapped register access
  • References provide:
    • Safer APIs when null is not a valid state
    • Cleaner and more readable code

Understanding both is essential for writing reliable firmware and reviewing low-level APIs.
 

Loading...

Input

5

Expected Output

After incrementPtr: 6 After incrementRef: 6