Skip to the page

Programming basics · Write code

A swap function that doesn't swap

The interviewer asks

What does this C++ program print, and why does each swap behave the way it does?

#include <iostream>
using namespace std;

void swap1(int a, int b)   { int t = a; a = b; b = t; }
void swap2(int *a, int *b) { int t = *a; *a = *b; *b = t; }
void swap3(int &a, int &b) { int t = a; a = b; b = t; }

int main() {
    int x = 1, y = 2;
    swap1(x, y);   cout << x << " " << y << endl;
    swap2(&x, &y); cout << x << " " << y << endl;
    swap3(x, y);   cout << x << " " << y << endl;
    return 0;
}

Then

Follow-ups the interviewer asks next

  1. Why does swap1 change nothing outside?
  2. What's the difference between passing a pointer and passing a reference?
  3. Can a reference be NULL, or be made to refer to something else later?
  4. Does C have call by reference?
  5. How does Java pass arguments?
  6. Why pass a big object as const Student&?

The answer

What a strong answer covers

  • Output: 1 2, then 2 1, then 1 2.
  • swap1 is call by value: it swaps its own copies, so x and y don't change.
  • swap2 gets the addresses of x and y and swaps the values stored there.
  • swap3 takes references, other names for x and y, so it really swaps them, back to 1 2.
  • A pointer is a variable holding an address: it can be NULL, can be pointed elsewhere, and needs * and &. A reference is another name for an existing variable: it must be set when created and can't be reseated or (in valid code) be null.
  • C has only call by value; passing a pointer by value gives the same effect as passing by reference.
  • Java always passes by value. For objects the value is a reference, so changes to the object's fields show outside, but assigning a new object to the parameter doesn't.
  • const T& avoids copying a big object and promises not to change it.

The red pen

Common traps

Avoid:"2 1" after swap1; "C has call by reference"; "Java passes objects by reference".

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview