Consider this C code to swap two integers and these five statements after it:…

2006

Consider this C code to swap two integers and these five statements after it:

void swap(int *px, int *py) 
{ 
   *px = *px - *py; 
   *py = *px + *py; 
   *px = *py - *px; 
}

S1: will generate a compilation error S2: may generate a segmentation fault at runtime depending on the arguments passed S3: correctly implements the swap procedure for all input pointers referring to integers stored in memory locations accessible to the process S4: implements the swap procedure correctly for some but not all valid input pointers S5: may add or subtract integers and pointers.

  1. A.

    S1

  2. B.

    S2 and S3

  3. C.

    S2 and S4

  4. D.

    S2 and S5

Attempted by 168 students.

Show answer & explanation

Correct answer: C

Answer: S2 and S4

Explanation:

  • S2 (may generate a segmentation fault at runtime depending on the arguments passed): True. If either pointer argument is null, uninitialized, or points to memory the process cannot access, dereferencing it causes undefined behavior (commonly a segmentation fault).

  • S4 (implements the swap procedure correctly for some but not all valid input pointers): True. For two distinct, accessible pointers and when the integer arithmetic does not overflow, the three-step subtraction/addition sequence swaps the values. However, it fails when both pointers refer to the same integer (it will zero the value) and can invoke undefined behavior if signed integer overflow occurs.

  • S1 (will generate a compilation error): False. The code is syntactically valid C and should compile.

  • S3 (correctly implements the swap procedure for all input pointers referring to integers stored in memory locations accessible to the process): False. Even when pointers point to accessible memory, the algorithm fails for the aliasing case (both pointers equal) and may have undefined behavior if addition/subtraction overflows a signed int.

  • S5 (may add or subtract integers and pointers): False. The code performs arithmetic on the values obtained by dereferencing the pointers (*px and *py), which are integers. It does not perform arithmetic on the pointer values themselves.

Note: A simple, safe swap uses a temporary integer: int t = *px; *px = *py; *py = t; This avoids aliasing issues and signed overflow remains the only arithmetic concern if you perform arithmetic-based swaps.

Explore the full course: Gate Guidance By Sanchit Sir