俩道厉害的面试题

来源:互联网 发布:tensorflow支持的显卡 编辑:程序博客网 时间:2024/05/02 03:29

选自论坛:http://bbs.csdn.net/topics/370070922

  1.不用局部变量和全局变量实现strlen;
  2.有2数据,写一个交换数据的宏;

 

先自己思考:

---------------------------------------------------------------------------

 

1解答:

size_t strlen(const char *str)
{
    return *str==0 ? 0 : 1+strlen(str+1);
}
 
PS:附strlen源码解析:http://blog.csdn.net/dw903632958/article/details/8929934 

2解答:

赵老师神作@zhao4zhong1

 

#include <stdio.h>#define SWAP(a,b) ((&(a))!=(&(b)))?((a)^=(b)^=(a)^=(b)):((a)=(a))char    c1=1   ,c2=2   ;short   s1=1   ,s2=2   ;int     i1=1   ,i2=2   ;__int64 I1=1i64,I2=2i64;float   f1=1.0f,f2=2.0f;double  d1=1.0 ,d2=2.0 ;void main() {    SWAP(c1,c2);                          printf("char       %5d,   %5d\n",c1,c2);    SWAP(s1,s2);                          printf("short      %5d,   %5d\n",s1,s2);    SWAP(i1,i2);                          printf("int        %5d,   %5d\n",i1,i2);    SWAP(I1,I2);                          printf("__int64 %5I64d,%5I64d\n",I1,I2);    SWAP(*(int     *)&f1,*(int     *)&f2);printf("float      %5g,   %5g\n",f1,f2);    SWAP(*(__int64 *)&d1,*(__int64 *)&d2);printf("double    %5lg,  %5lg\n",d1,d2);     SWAP(c1,c1);    printf("%d\n",c1);}//char           2,       1//short          2,       1//int            2,       1//__int64     2,    1//float          2,       1//double        2,      1//2


 


原创粉丝点击