OA. free
Free
Qualcomm Embedded Systems & Hardware Embedded Systems & Hardware Medium

Identify the error in the given C code snippet:

Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.

Identify the error in the given C code snippet:

#include <stdio.h>

int main() {
    int x = 5;
    int y = 10;
    swap(x, y);
    printf("After swapping: x = %d, y = %d\n", x, y);
    return 0;
}

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}
Choose one option.
Show answer & explanation
Answer: B. Incorrect use of pointers: swap expects pointer arguments (&x, &y), but integer values are passed

The swap function is declared to take two int* (pointer to int) parameters, but the function call swap(x, y) passes integer values directly instead of their addresses. The correct call should be swap(&x, &y) to pass pointers to the variables so they can be modified. Without this, the code will fail to compile with a type mismatch error.

Step-by-step Derivation:
Analysis of the code flow:

  1. Function declaration: void swap(int *a, int *b) expects two pointers to integers.
  2. Function call: swap(x, y) passes two integer values (not pointers).
  3. Type mismatch: int cannot be implicitly converted to int*.
  4. Compiler error: "incompatible type for argument" or similar.
  5. Fix: Change the call to swap(&x, &y) to pass addresses using the address-of operator &.
  6. Option A is incorrect: main() has a return statement (return 0).
  7. Option C is incorrect: printf format specifiers %d correctly match int arguments.
  8. Option D is incorrect: temp is properly declared as int and can hold integer values.