Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding poorly written code, 2nd year CS past paper [closed]

The question is to describe what the code does, what the function does.

The following code is part of the past exam papers for a 2nd year C and C++ module. The task is to describe what the following piece of code does. I've written the code exactly as presented, with some comments added by myself.

int g(int * y, unsigned size, int z) {
    int tmp = y[0];
    // what type is unsigned size? Int I presume. Why would you add an int to an array of ints?
    int * b = y + size; 
    y[0] = z;
    // I have the most difficulty understanding the following.
    while (1) if (*(--b)==z){y[0] = tmp; return b - y;};
    // are the following 3 lines ever even reached?
    y[0] = tmp;
    if (tmp == z) return 0;
    else return -1;
}
like image 222
Mike Gallagher Avatar asked Apr 16 '12 15:04

Mike Gallagher


1 Answers

// what type is unsigned size?

It's an unsigned int called size. You add it to a pointer as in normal pointer arithmetic - advance this pointer to the very end of the array.

while (1) if (*(--b)==z){y[0] = tmp; return b - y;};

OK, we've got

  • while(1) = while(true), or 'loop forever'
  • *(--b) pre-decrement b and read the value from that index of the array
  • if we've found z, replace the first element with the value we read from it and return b-y - pointer arithmetic for the array index we're at

i.e. we're scanning backwards through the array to find the last instance of z and returning the index at which we found it. We will always find z in the array because we put it there as the first element, i.e. if z isn't in the array then we return 0.

// are the following 3 lines ever even reached?

No, I don't think so.

like image 147
Rup Avatar answered Sep 19 '22 07:09

Rup