各種程式坑集合

C++

隱式類型轉換bug

vector.size() is unsigend int

發生情況

  // vector is empty
  int i = 4;
  if (0 <= i && i <= vector.size() - 1)
    cout << vector.size() << endl;
  cout << i << endl;

其他問題

在宣告class盡量不要使用字串以免型別有問題

Macro

由於程序員忘記其為巨集導致多次計算

#define max(a, b) ((x) > (y) ? (x) : (y))

void example()
{
  int x = 2, y = 10;
  int z = max(x, ++y) 
}

參見以下兩個資源的章節


  1. Goodliffe, P., 2014. Becoming a Better Programmer: A Handbook for People Who Care About Code. " O’Reilly Media, Inc.". ↩︎

  2. Raymond, E.S., 2003. The art of Unix programming. Addison-Wesley Professional. ↩︎


C++