-
Failure to include necessary headers
1 // Missing: #include <iostream>
2 // Missing: #include <string>
3
4 int main() {
5 std::string name;
6 std::cout << "Enter your name: ";
7 std::cin >> name;
8 std::cout << "Hello, " << name << "!" << std::endl;
9 return 0;
10 }
-
Not using namespaces for functions or operators
1 // Missing: using namespace std;
2
3 int main() {
4 string name;
5 cout << "Enter your name: ";
6 cin >> name;
7 cout << "Hello, " << name << "!" << endl;
8 return 0;
9 }
-
Incorrectly using assignment operators instead of equality operators
1 int x = 5;
2 int y = 10;
3
4 if (x = y) { // This is an assignment operator, not a comparison operator
5 cout << "x and y are equal." << endl;
6} else {
7 cout << "x and y are not equal." << endl;
8 }
-
Infinite loops caused by not updating loop variables or conditions
1 int x = 0;
2 while (x < 10) {
3 cout << x << endl;
4 // Missing: x++;
5 }
-
Dereferencing null pointers
1 int* ptr = nullptr;
2 *ptr = 10; // This is an error, because we're dereferencing a null pointer
-
Incorrect memory management
1 int* x = new int[10];
2 delete x; // This is incorrect, because it should be delete[] x;
-
Using the wrong form of string concatenation
1 std::string a = "Hello, ";
2 std::string b = "World!";
3 std::string c = a + b; // This is correct
4
5 // Incorrect: c = &a + &b;
-
Failure to properly handle scope
1 for (int i = 0; i < 10; i++) {
2 // This is fine
3 }
4
5 cout << i << endl; // This is an error, because 'i' is out of scope
-
Using global variables when they are not necessary
1 // This is fine
2 int global_variable = 0;
3
4 void some_function() {
5 global_variable++;
6 }
7
8 // This is generally better
9 int some_function() {
10 static int static_variable = 0;
11 static_variable++;
12 return static_variable;
13}
-
Failure to validate user input
1 int x;
2 cout << "Enter a number: ";
3 cin >> x;
4
5 // This is incorrect, because the program assumes the user will enter a valid number
6 if (x < 10) {
7 cout << "The number is less than
10." << endl;
8} else {
9 cout << "The number is 10 or greater." << endl;
10 }
About Author
Discover more from SURFCLOUD TECHNOLOGY
Subscribe to get the latest posts sent to your email.