【C++】编程规范之表达式原则

  1. 表达式中变量的位置
    在编写表达式时,将变量放置在右边,可以提高代码的可读性和可理解性。这种做法符合自然语言的阅读习惯,使得代码更易于理解。
cpp 复制代码
// Good
if (5 == x) {
    // do something
}

// Avoid
if (x == 5) {
    // do something
}
  1. 不变量和资源申请的优化
    将不变量的计算和资源申请移到循环外部,可以减少重复计算和资源申请的次数,提高代码的效率和性能。
cpp 复制代码
// Good
const int n = calculateSize();
vector<int> nums(n, 0); // Resource allocation outside the loop

for (int i = 0; i < n; ++i) {
    // do something with nums[i]
}

// Avoid
for (int i = 0; i < calculateSize(); ++i) {
    vector<int> nums(calculateSize(), 0); // Resource allocation inside the loop
    // do something with nums[i]
}
  1. 内存申请的优化
    重复内存申请会增加系统开销,容易导致内存碎片。因此,将内存申请移到循环外部,并尽量减少申请次数,可以提高代码的性能和效率。
cpp 复制代码
// Good
vector<int> nums(n, 0); // Memory allocation outside the loop

for (int i = 0; i < n; ++i) {
    // do something with nums[i]
}

// Avoid
for (int i = 0; i < n; ++i) {
    vector<int> nums(1, 0); // Memory allocation inside the loop
    // do something with nums[i]
}
  1. 浮点数比较的注意事项
    在比较浮点数时,应该避免使用相等(==)或不等(!=)操作符,而应该使用范围判断(>=、<=)结合一个极小的误差值(epsilon),以防止由于精度问题而导致的错误判断。
cpp 复制代码
// Good
const double epsilon = 1e-9;
if (fabs(a - b) <= epsilon) {
    // a and b are considered equal
}

// Avoid
if (a == b) {
    // This might lead to incorrect results due to floating point precision issues
}
  1. 数据类型的选择
    在处理数据时,应根据需求选择合适的数据类型,以避免数据溢出和精度丢失等问题。
cpp 复制代码
// Good
int64_t result = static_cast<int64_t>(a) * b;

// Avoid
int result = a * b; // This might cause overflow if a and b are large integers

注意

编写高质量的代码不仅可以提高系统的稳定性和可维护性,还可以提高开发效率和团队协作效率。通过遵循上述规则,开发人员可以写出更加优雅、高效和可靠的代码,为项目的成功贡献力量。

相关推荐
handler016 分钟前
算法:Trie树(字典树)
c语言·数据结构·c++·笔记·算法·深度优先
思麟呀6 分钟前
应用层自定义协议与序列化
linux·运维·服务器·网络·c++
ZPC82107 分钟前
PPO (Proximal Policy Optimization) 算法模块详细拆解
人工智能·pytorch·算法·机器人
6+h10 分钟前
【Redis】数据结构讲解
数据结构·数据库·redis
阿Y加油吧10 分钟前
力扣打卡day06——滑动窗口最大值、最小覆盖子串
数据结构·算法·leetcode
沉鱼.4411 分钟前
日期题目集
数据结构·算法
坚定学代码14 分钟前
qt c++ 局域网聊天小工具
c++·qt·个人开发
晓纪同学18 分钟前
EffctiveC++_01第一章
java·开发语言·c++
Book思议-19 分钟前
【数据结构考研真题】链表题
c语言·数据结构·算法·链表·408·计算机考研
lifallen19 分钟前
从零推导一个现代 ReAct Agent框架
人工智能·算法·语言模型