赞
踩
// Good
if (5 == x) {
// do something
}
// Avoid
if (x == 5) {
// do something
}
// 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]
}
// 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]
}
// 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
}
// 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
注意
编写高质量的代码不仅可以提高系统的稳定性和可维护性,还可以提高开发效率和团队协作效率。通过遵循上述规则,开发人员可以写出更加优雅、高效和可靠的代码,为项目的成功贡献力量。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。