现在的位置: 首页 > 综合 > 正文

编程技巧

2013年10月07日 ⁄ 综合 ⁄ 共 1060字 ⁄ 字号 评论关闭

1.对结构体的初始化

      struct s{

int a;

int b;

  }

  int main()

{

 strucnt s huang={1,3};

}

其实这种初始化的方法是存在风险的假如某天对该结果体中添加了元素,变量的顺序自然就发生了改变,这样将导致不可预测的结果

比较安全的写法:

  struct s huang={.a=1,.b=3};

注意有的编译器不支持该赋值的方法

 

2返回指向临时变量的指针

1..char* get_str(void)
{
    char str[] = {"abcd"};
    return str;
}

2.char* get_str(void)
{
    char* str = {"abcd"};
    return str;
}

int main(int argc, char* argv[])
{
    char* p = get_str();
    printf("%s\n", p);
    return 0;
}

开始的时候可能并没有发现什么不对劲的地方,在1中abcd字符串是在str指向的栈中,返回时被释放。而2中abcd实际上是在rodata中,str就指向了这个地址,指针自然能够返回

 

3.使用goto和do{ }  while(0)进行错误处理

  (1)

   dlist_lock(thiz);
    if((node = dlist_create_node(thiz, data)) == NULL)
    {
        ret = RET_OOM;
        goto done;
    }
    if(thiz->first == NULL)
    {
        thiz->first = node;

        goto done;

 }

 done:
    dlist_unlock(thiz);
    return ret;

  (2)使用do while

          dlist_lock(thiz);
    do
    {
        if((node = dlist_create_node(thiz, data)) == NULL)
        {
            ret = RET_OOM;
            break;
        }
        if(thiz->first == NULL)
        {
            thiz->first = node;

                      break;
        }
        ...
    }while(0);   ///here
    dlist_unlock(thiz);
    return ret;
}

    

抱歉!评论已关闭.