我在面试中被问到了这个问题,它看起来很简单,但我想确认一下我对它的功能理解是否正确。
我在面试中被问到以下问题:
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--);
}
}
我在面试中被问到以下问题:
- 这个函数是用来干什么的?
- 为什么有人会写出那么复杂的代码?
- 有没有其他方法可以写得更简单、更快速一些?
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.