0
点赞
收藏
分享

微信扫一扫

学习笔记——C语言基本概念&结构体&共用体&枚举——(10)

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

// Avoid
if (x == 5) {
    // do something
}
  1. 不变量和资源申请的优化
    将不变量的计算和资源申请移到循环外部,可以减少重复计算和资源申请的次数,提高代码的效率和性能。
// 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. 内存申请的优化
    重复内存申请会增加系统开销,容易导致内存碎片。因此,将内存申请移到循环外部,并尽量减少申请次数,可以提高代码的性能和效率。
// 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),以防止由于精度问题而导致的错误判断。
// 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. 数据类型的选择
    在处理数据时,应根据需求选择合适的数据类型,以避免数据溢出和精度丢失等问题。
// 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

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

举报

相关推荐

0 条评论