C++ Syntax
C++ syntax defines how C++ code must be written. Let us break down a small program line by line.
C++ Program Structure
#include <iostream> // header for input/output
int main() { // program starts here
std::cout << "Line 1" << '\n';
std::cout << "Line 2" << std::endl;
}Line 1 Line 2
Key C++ Syntax Rules
- Statements end with a semicolon.
- Curly braces { } define blocks such as function bodies.
- C++ is case-sensitive.
- std:: means the name comes from the standard library namespace.
- << sends values to an output stream and can be chained.
- Comments use // for one line and /* */ for several lines.
Namespaces and using
Writing using namespace std; lets you drop std::, but in larger code it can cause name clashes. A good middle ground is to import only what you need.
#include <iostream>
using std::cout;
int main() {
cout << "Only cout was imported\n";
}Only cout was imported
endl vs \n
std::endl prints a newline and also flushes the output buffer, which is slower when printing many lines. Prefer '\n' unless you specifically need a flush.
Frequently asked questions
Should I use using namespace std?
It is fine in tiny learning programs, but avoid it in headers and large projects because it imports hundreds of names and can cause conflicts.
What does std:: mean in C++?
std is the namespace of the C++ Standard Library. std::cout means "the cout that belongs to std".
What is the difference between endl and \n?
Both end the line. std::endl also flushes the stream, which forces output to be written immediately and is slower in loops.