-
包含头文件时,推荐使用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;
C++代码review问题<一>
最新推荐文章于 2022-07-04 10:14:21 发布