【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

注意

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

相关推荐
NiceCloud喜云3 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
小羊在睡觉3 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
cjhbachelor3 小时前
c++继承
c++
3DVisionary3 小时前
蓝光三维扫描:医疗制造的精度焦虑怎么解
人工智能·算法·制造·蓝光三维扫描·医疗制造·三维检测·义齿检测
好评笔记3 小时前
机器学习面试八股——常用损失函数
人工智能·深度学习·算法·机器学习·校招
weixin_468466853 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
肩上风骋3 小时前
C++14特性
开发语言·c++·c++14特性
_日拱一卒4 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
珂朵莉MM4 小时前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--束搜索
人工智能·算法
Omics Pro5 小时前
首个!外源天然产物综合性代谢图谱
数据库·人工智能·算法·机器学习·r语言