【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

注意

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

相关推荐
闻道且行之33 分钟前
TurboOCR:基于PP-OCRv6的极速Windows离线OCR工具,深度解析3.4GB依赖背后的技术架构
c++·人工智能·python·qt·机器学习·ocr
QXWZ_IA3 小时前
1库1图1批是什么?千寻位置公安地图数据体系详解
科技·算法·能源·媒体·交通物流·政务
c238563 小时前
Bug 猎手入门指南
c++·算法·bug
Reart4 小时前
Leetcode 213.打家劫舍2(内含闲谈,打劫真是技术活,好题,716)
后端·算法
Reart5 小时前
Leetcode 198.打家劫舍(716)
后端·算法
Jerry5 小时前
LeetCode 110. 平衡二叉树
算法
玖玥拾5 小时前
C++ 数据结构 八大基础排序算法专题
数据结构·c++·算法·排序算法
Tim_105 小时前
【C++】017、new/delete与malloc/free的区别
java·数据结构·算法
YYYing.5 小时前
【C++大型项目之高性能服务器框架 (七) 】Socket与ByteArray模块
服务器·c++·后端·框架·高性能·c/c++