Consider these two functions and two statements S1 and S2 about them C int…

2006

Consider these two functions and two statements S1 and S2 about them

C

int work1(int *a, int i, int j)
{
    int x = a[i+2];
    a[j] = x+1;
    return a[i+2] – 3;
}

int work2(int *a, int i, int j)
{
    int t1 = i+2;
    int t2 = a[t1];
    a[j] = t2+1;
    return t2 – 3;
}

S1:

The transformation form work1 to work2 is valid, i.e., for any program state and input arguments, work2 will compute the same output and have the same effect on program state as work1

S2:

All the transformations applied to work1 to get work2 will always improve the performance (i.e reduce CPU time) of work2 compared to work1

  1. A.

    S1 is false and S2 is false

  2. B.

    S1 is false and S2 is true

  3. C.

    S1 is true and S2 is false

  4. D.

    S1 is true and S2 is true

Attempted by 35 students.

Show answer & explanation

Correct answer: A

S1 is false because work1 and work2 may behave differently if a[i+2] accesses an invalid memory location, such as when i+2 exceeds array bounds. In work1, a[i+2] is accessed twice, and if the pointer is invalid, undefined behavior may occur. In work2, t1 = i+2 is computed once and stored in a variable, but the access to a[t1] still depends on valid indexing. However, if i+2 is out of bounds, both functions may exhibit undefined behavior, but the transformation isn't guaranteed to preserve semantics in all cases. S2 is false because performance improvements depend on compiler optimizations and hardware; the transformation doesn't inherently reduce CPU time. Therefore, both statements are false.

Explore the full course: Gate Guidance By Sanchit Sir