First Program Β» Common Problems
It is worth paying attention to what can cause a compilation error. Compilation errors are caused by invalid C++. When the compiler encounters invalid code, it will stop and tell you what's wrong. You cannot run your program unless compilation is completed without errors.
Forgetting about std::
prefixβ
An error is caused if you omit std::
without the appropriate using
statement.
π΄ Error messageβ
- GCC
- MSVC
π Solutionβ
Add using std::cout;
to the top of your main
function:
#include <iostream>
int main() {
using std::cout;
cout << "Hello, World!";
}
Forgotten includesβ
It's very easy to forget an #include
, even for experts.
π΄ Error messageβ
- GCC
- MSVC
Missing semicolons ;
β
Beginners often forget the semicolons (;
) at the end of statements.
Study the code examples provided in this lesson carefully, paying attention
to where they should go.
π΄ Error messageβ
- GCC
- MSVC
Compilers have to guess where you missed a semicolon. Therefore if you are sure that you didn't miss a semicolon on the line it tells you about, try looking up a few lines.
Additionally missing semicolons can also cause unrelated errors further down your code. Usually the first error message given by the compiler is the most helpful one.
Unterminated textβ
Text is always between the quote characters "TEXT IS HERE!"
.
Forgetting to add the second quotation mark leads to compiler thinking the rest of your program is text
causing numerous errors.
π΄ Error messageβ
- GCC
- MSVC
Using "
inside of textβ
You may be tempted to put quotes inside a message when outputting it to the console.
However, remember that C++ considers everything inside of "..."
quotes to be text.
Thus, if you write:
"Hi! My name is "Slim Shady". Nice to meet you!"
C++ will interpret this as:
"TEXT" C++ CODE "TEXT"
π΄ Error messageβ
- GCC
- MSVC
error: unable to find string literal operator βoperator""Slimβ with βconst char [16]β, βlong unsigned intβ arguments
πΌ Illustration of the error:β
TODO
error C3688: invalid literal suffix 'Slim'; literal operator or literal operator template 'operator ""Slim' not found
error C2146: syntax error: missing ';' before identifier 'Shady'
error C2065: 'Shady': undeclared identifier
error C2143: syntax error: missing ';' before 'string'
πΌ Illustration of the error:β
These error messages aren't that helpful! Your hint should be the fact that it is treating what you intend to be text as code.
π Solutionβ
You can prevent this by using the \
backslash character to escape the quote.
"Hi! My name is \"Slim Shady\". Nice to meet you!"
The \"
is an example of an escape sequence. It tells the compiler to treat the next character as text.
We can also use the backslash to escape other characters, such as the backslash itself. As a result, we'll need to use two backslashes to get one in the output.
std::cout << "C:\\Users\\SlimShady\\Desktop";
C:\Users\SlimShady\Desktop