2. Pointer vs Reference Swap

#include <iostream>

void swapPtr(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void swapRef(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int x, y;
    std::cin >> x >> y;

    int a = x, b = y;
    swapPtr(&a, &b);
    std::cout << "After swapPtr: a=" << a << " b=" << b << "\n";

    int c = x, d = y;
    swapRef(c, d);
    std::cout << "After swapRef: a=" << c << " b=" << d;

    return 0;
}

Solution Details

  • swapPtr uses explicit memory access via pointers
  • swapRef uses reference binding with no dereferencing
  • Both perform in-place swaps with O(1) time and memory

Embedded Relevance

  • Demonstrates:
    • Pass-by-address (C-style APIs)
    • Pass-by-reference (C++ firmware abstractions)
  • Foundational for:
    • Register access
    • Peripheral drivers
    • HAL / BSP API design

 

 

 

Loading...

Input

5 10

Expected Output

After swapPtr: a=10 b=5 After swapRef: a=10 b=5