AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Easyccall by value

~60s

A swap that does not swap

What does this C program print?

#include <stdio.h>

void swap(int a, int b) {
    int t = a;
    a = b;
    b = t;
}

int main(void) {
    int x = 3, y = 8;
    swap(x, y);
    printf("%d %d", x, y);
    return 0;
}
Show the answer and the worked solution

Correct answer: A.

3 8

Worked solution

  1. C passes arguments by value, so a and b are private copies of x and y.
  2. The three lines do exchange those copies, leaving a = 8 and b = 3 inside the function.
  3. The copies vanish when swap returns, so x is still 3 and y is still 8, and the program prints 3 8.

Answer: 3 8.

The idea

C has only call by value, so a function can never change a caller's variable unless it is handed the address of that variable. Passing int * instead of int is the fix.

Shortcut. swap receives copies and returns nothing, so main's x and y cannot change: print them exactly as declared, 3 8.

Common trap. "8 3" trusts the function's name; the exchange happens only between the private copies a and b, which vanish on return.

A swap that does not swap — Aptitude Question

A swap that does not swap: What does this C program print? Answer and worked solution on CodeKairo.

Question

What does this C program print?

#include <stdio.h>

void swap(int a, int b) {
    int t = a;
    a = b;
    b = t;
}

int main(void) {
    int x = 3, y = 8;
    swap(x, y);
    printf("%d %d", x, y);
    return 0;
}

Options

  1. 3 8
  2. 3 3
  3. 8 3
  4. 8 8
Show the answer and the worked solution

Correct answer: A. 3 8

Worked solution

  1. C passes arguments by value, so a and b are private copies of x and y.
  2. The three lines do exchange those copies, leaving a = 8 and b = 3 inside the function.
  3. The copies vanish when swap returns, so x is still 3 and y is still 8, and the program prints 3 8.

Answer: 3 8.

The idea

C has only call by value, so a function can never change a caller's variable unless it is handed the address of that variable. Passing int * instead of int is the fix.

Shortcut. swap receives copies and returns nothing, so main's x and y cannot change: print them exactly as declared, 3 8.

Common trap. "8 3" trusts the function's name; the exchange happens only between the private copies a and b, which vanish on return.

All Programming Fundamentals questions · placement mock tests