Skip to content
Official PYQ · 2006

GATE CS 2006 Q57 — Programming in C

Explain with AI

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

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

Choose one option
View worked solution

Answer: C

To determine which statements are correct, let us analyze each of them:

  • S1 (False): The code is syntactically valid in C. It dereferences integer pointers and performs standard integer arithmetic, so it will compile without errors.
  • S2 (True): If either px or py is a NULL pointer or points to an invalid/unmapped memory address, dereferencing them (e.g., *px) will cause a segmentation fault at runtime.
  • S3 (False) & S4 (True): Let us trace the code when both pointers point to the same memory location (aliasing), i.e., px == py. Let the value at this location be VV.
    1. *px = *px - *py;   ⟹  ∗px=V−V=0\implies *px = V - V = 0
    2. *py = *px + *py;   ⟹  ∗py=0+0=0\implies *py = 0 + 0 = 0
    3. *px = *py - *px;   ⟹  ∗px=0−0=0\implies *px = 0 - 0 = 0
    The value at the memory location becomes 00 instead of remaining VV. Thus, the swap fails when the pointers are identical. It only works correctly when px != py. Hence, it works for some but not all valid pointers.
  • S5 (False): The operations are performed on *px and *py, which are of type int, not on the pointers px and py themselves. No pointer arithmetic is involved.

Thus, only statements S2 and S4 are correct, which corresponds to option C.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions