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!
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;
2. Using = instead of == in conditions
if (marks = 50) { // assigns 50, always true
cout << "Pass";
}
Fix: use == to compare. Many developers turn on compiler warnings (-Wall) so the compiler catches this for them.
if (marks == 50) { ... }
3. Off-by-one errors in loops
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i <= 5; i++) { // arr[5] does not exist
cout << arr[i];
}
An array of size 5 has indexes 0 to 4.
Fix: loop with i < 5, or better, use a range-based loop:
for (int x : arr) cout << x << " ";
4. Integer division surprises
int a = 7, b = 2;
double avg = a / b; // 3, not 3.5
Both operands are int, so C++ does integer division first, then converts.
Fix: make one side a double.
double avg = static_cast<double>(a) / b; // 3.5
5. Mixing cin >> and getline
int age;
string name;
cin >> age;
getline(cin, name); // reads an empty line!
cin >> age leaves the newline in the input buffer, and getline reads it immediately.
Fix: clear the leftover newline first.
cin >> age;
cin.ignore();
getline(cin, name);
6. Missing break in switch
switch (choice) {
case 1: cout << "Add";
case 2: cout << "Delete"; // runs too when choice is 1
}
Fix: end each case with break; unless you really want it to fall through.
7. Passing big objects by value
void printList(vector<int> v) { ... } // copies the whole vector
Fix: pass by const reference when you only need to read it.
void printList(const vector<int>& v) { ... }
Wrapping up
Almost every beginner hits these, so don't worry if you recognized a few. Turn on compiler warnings, test with small inputs, and read error messages slowly; they usually point right at the problem.
If you want a structured path from the very basics (variables, loops, functions, arrays, pointers, OOP) with worked examples and practice questions, I wrote a beginner-friendly ebook: C++ Programming for Beginners — https://farhanbreeze4.gumroad.com/l/kxwlwo
Which of these mistakes got you first? Drop it in the comments.
Top comments (0)