When you start learning C++, the compiler can feel like it's out to get you. Most of the time, though, beginners trip over the same handful of mistakes. Here are seven I see again and again, with a quick fix for each.
1. Forgetting to initialize variables
int total ; total = total + 5 ; // total holds garbage!
Enter fullscreen mode
Exit fullscreen mode
In C++, a local variable is not set to zero for you. It holds whatever was in that memory before.
Fix: always give variables a starting value.
int total = 0 ; total += 5 ;
Enter fullscreen mode
Exit fullscreen mode
2. Using = instead of == in conditions
if ( marks = 50 ) { // assigns 50, always true cout << "Pass" ; }
Enter fullscreen mode
Exit fullscreen mode
Fix: use == to compare. Many developers turn on compiler warnings ( -Wall ) so the compiler catches this for them.
if ( marks == 50 ) { ... }
Enter fullscreen mode
Exit fullscreen mode
3.…