Common Mistakes in C++

Summary

This post will be updated from time to time. The post contains some mistakes that I will make in work and study when coding in C++.

Contents

  1. container.size() – 1 when the container is empty
  2. negative % positive
  3. ‘+’ does work in “C_String”
  4. remember to delete after new
  5. to_string(‘a’)
  6. signed integers compared to unsinged integers in min or max
  7. variable– when it has type size_t

Mistakes

1. container.size() – 1 when the container is empty

vector<int> nums;
// correct version
for (size_t i = 0; i + 1 < nums.size(); ++i) {
    // ...
}

// wrong, nums.size() - 1 will overflow for unsigned int, which couses i < (-xxx) hold forever
for (size_t i = 0; i < nums.size() - 1; ++i) {
    // ...
}

2. negative % positive

cout << -11 % 10 << endl; // -1
cout << -1 % 10 << endl; // -1
cout << 1 % 10 << endl; // 1

3. ‘+’ does work in “C_String”


“123” is a c_string in c++.

#include <string>
std::string wrong= "1" + "1"; // ERROR, + operator is overloaded for C++ string
std::string right= std::string("1") + "1"; // 11

std::string result;
char a = 'a';
result += "1221" + a; // ERROR 

4. remember to delete after new


In projects containing only one thread, you may not meet a killed. It is different when you use multiple threads and without delete your program will be killed soon.

5. to_string(‘a’)

cout << to_string('a') << endl; // 97
cout << to_string(1, 'a') << endl; // 'a' 

6. signed integers compared to unsinged integers in min or max

vector<int> a {1,2,3};
min(a[0], a.size() - 1); // can not compile, arguments in min should have the same types

7. variable– when it has type size_t

vector<int> A {1, 2, 3};
for (size_t i = A.size() - 1; i >= 0; --i) {
        do_something();
}

It is an endless loop similar to mistake 1.

Leave a Reply

Your email address will not be published. Required fields are marked *