C++代码review问题<一>

  • 包含头文件时,推荐使用c++风格(有争议)
    详细讨论见知乎帖子:https://www.zhihu.com/question/51288493
    看下来一句话:都可以,c++风格代码风格会优雅些

     #include <stdio.h>  // bad
     #include <cstdio> // good
    
  • 非必要情况下,不使用无符号类型(有争议)
    主要遵循c++ google style:

    You should not use the unsigned integer types such as uint32_t, unless there is a valid reason such as representing a bit pattern rather than a number, or you need defined overflow modulo 2^N. In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this.

    无符号类型与有符号类型数字在一起运算时,结果未知:

    
    

    下溢导致死循环

     for(unsigned int i = 100; i >= 0; i--) {
        Print(array[i]);
    }
    
  • 定义enum时,使用enum class
    enum class 类型安全, enum类型不安全
    stackoverflow答案

    #include <cstdio>
     enum Week {
         kMonday = 1,
         KTuesday,
         kWednesday,
         kThursday,
         kFriday,
         kSaturday,
         kSunday,
     };
    
      enum class Week1 {
         kMonday = 1,
         KTuesday,
         kWednesday,
         kThursday,
         kFriday,
         kSaturday,
         kSunday,
     };
     
     int main()
     {
         Week w = Week::kMonday;
         int i = w; // compiler success
         Week1 w1 = Week1::kMonday;
         int j = w1; // compiler failed
     }
    
    
  • 定义宏函数时,使用do {}while(0);方式

    #include <cstdio>
    
    #define FUNC(i)\
    {\
    printf("i:%d\n", i);\
    }
    
    using namespace std; 
    int main()
    {
    	int i = 3;
    	FUNC(i);
        if(i > 0)
        	FUNC(i); // compile failed
        else
            printf(""); 
    }
    

    上述代码代码会编译失败,因为if…else…经过宏展开后,代码如下

    if(i > 0)
    	{
    	printf("i:%d\n", i)
    	}; // 此处的; 引起编译出错
    else
       printf(""); 
    
  • 当在cpp文件中声明并定义变量或方法时建议放到匿名空间
    cpp文件中声明的变量和方法,放到匿名命名空间(c语言增加static),声明连接属性为internal linkage,这样其他文件无法使用该变量或方法,提高代码封装性。

  • c++代码中的struct关键字可以省略

    更加像C++,节省编写字符

    c语言声明struct,一个技巧是使用typedef可以达到省略struct关键字

    typedef struct {
    	char* name;
    	int id;
    } People;
    
    People p1;
    People p2;
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值