I got this question in interview, it seems simple one but I want to confirm my understanding about its functioning.
f (char *p, char *q, int n)
{
int i1 = n >> 2;
int i2 = n & 3;
switch (i2)
{
do {
*q++ = *p++;
case 3: *q++ = *p++;
case 2: *q++ = *p++;
case 1: *q++ = *p++;
case 0: ;
} while (i1--);
}
}
I was asked below questions in interview:
- What this function does?
- Why would somebody write such convoluted code?
- Is there any way to write it differently (simpler, faster)?
Answers given:
This function copies the number of elements from the memory where *P is pointing to the memory where *q is pointing.
if you will write it with for loop as below (writing only loop)
for(i=0;i<n;i++) *q++ = *p++;
then the compiler taking more MIPS/time in condition checking. In this it will first subtract i from n and then checks is I non zero ? In the given code while loop maintain condition only 1 condition if i1 is non-zero ? So in while loop there is less condition checking.
We can write as:
f (char *p, char *q, int n) { for(i=n;i--;) *q++ = *p++; }
It seems simple and faster to me.
Please give me your opinion.