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;
}
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:
- Function declaration:
void swap(int *a, int *b)expects two pointers to integers. - Function call:
swap(x, y)passes two integer values (not pointers). - Type mismatch:
intcannot be implicitly converted toint*. - Compiler error: "incompatible type for argument" or similar.
- Fix: Change the call to
swap(&x, &y)to pass addresses using the address-of operator&. - Option A is incorrect: main() has a return statement (return 0).
- Option C is incorrect: printf format specifiers
%dcorrectly match int arguments. - Option D is incorrect: temp is properly declared as int and can hold integer values.