Forgetting Semicolons

What happens if I forget to put a semicolon at the end of a line?

When you forget a semicolon in C++, the compiler will generate an error because it can't figure out where one statement ends and the next begins. The error messages can sometimes be confusing though!

Let's look at an example:

#include <iostream>
using namespace std;

int main() {
  // missing semicolon!
  cout << "First line\n"   
  cout << "Second line\n";
}
error: expected ';' before 'cout'

The compiler tries to help by pointing to where it got confused, but sometimes the error appears on the line after the missing semicolon. This is because C++ doesn't know a statement is supposed to end until it hits either a semicolon or something that can't possibly be part of the current statement.

To make your code easier to debug:

  • Add semicolons as you write each line, don't wait until the end
  • When you get errors, always check the line before the error for a missing semicolon
  • Use proper indentation to make statement boundaries clearer
  • Most modern IDEs will highlight missing semicolons as you type

Remember: In C++, semicolons are statement terminators, not line terminators. This means you can actually write multiple statements on one line (though it's not recommended for readability):

#include <iostream>
using namespace std;

int main() {
  cout << "One"; cout << "Two"; cout << "Three";  
}
OneTwoThree

Setting up a C++ Development Environment

Getting our computer set up so we can create and build C++ programs. Then, creating our very first application

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Why Text Needs Quotes
Why do we need to use double quotes for text but not for numbers?
Program Closes Too Fast
Why does the program window close immediately after running?
Understanding std:: Prefix
Why do some code examples online use std::cout instead of just cout?
Understanding namespace std
Why do we need to write using namespace std; - what happens if we remove it?
Cross-Platform Code
How do I make my program work on both Windows and Mac without changing the code?
C++ File Extensions
What's the difference between 'main.cpp' and other file extensions like '.txt'?
Compiling vs Running
What's the difference between compiling and running a program?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant