44. Swap Two Values

#include <iostream>
using namespace std;

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;
    cin >> x >> y;

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

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

    return 0;
}

Solution Details

  • swapPtr → works with pointers, so we dereference *a and *b to swap the actual values.
     
  • swapRef → works with references, so a and b directly refer to the caller’s variables.
     
  • Both achieve the same result, but references avoid manual dereferencing and are easier to use.

     

👉 In simple words:

  • Pointer swap: “Give me your addresses, I’ll go swap the stuff at those addresses.”
  • Reference swap: “I already have a direct nickname for your variables, so I can swap them easily.”
     

Significance for Embedded Developers

  • Swapping values is common in buffer manipulation, sorting, and algorithm steps.
     
  • In low-level embedded code, pointers are often used (C-style).
     
  • In modern C++, references make the code safer and cleaner while achieving the same functionality.
     
Loading...

Input

5 10

Expected Output

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