【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

注意

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

相关推荐
木子算法几秒前
不是重心也不是中点:费马—韦伯点、它的最优性条件与迭代求解
人工智能·算法·目标跟踪
程序员AlbertTu30 分钟前
# Mantissa 使用教程 — Python 版与 C++ 版
c++·python·数值运算
Lazionr1 小时前
多态:从多种形态到运行时绑定
开发语言·c++
tryxr1 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_31 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
别动我齐刘海1 小时前
ROS2 Jazzy + C++ 实战路线——ros2_control
c++·人工智能·python·opencv·机器学习·机器人·github
Selvaggia1 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z2 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.2 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
码匠许师傅2 小时前
【C++三方组件】glog:Google 出品的 C++ 日志库
c++