C++ · Beginner
C++ Syntax and Your First Program
In short: A C++ program is a text file of statements that a compiler such as g++ turns into a native executable before anything runs. Execution starts in a function named main, #include lines bring in library names such as std::cout, every statement ends with a semicolon, and braces group statements into blocks.
What a C++ program is
C++ is a compiled language. You write source code in a file such as hello.cpp, hand it to a compiler, and the compiler checks the whole file and turns it into a native executable. Only then does anything run. That two-step cycle is why a typo shows up as a compiler error rather than as a crash later, and why the finished program runs on its own, with no interpreter installed.
Every program has exactly one function called main, and execution starts there. Above it sit #include lines, which paste in declarations from the standard library so the compiler knows what names such as std::cout mean. <iostream> provides the console input and output streams; <string> provides std::string.
Inside main, the work is done by statements. A statement is one instruction and ends with a semicolon; the compiler uses the semicolon, not the end of the line, to see where one statement stops. Braces { } group statements into a block, and a block is what gives a function its body. Line breaks and indentation exist for people: the compiler ignores them, so a long statement may be spread over several lines, as the third example shows.
Two details trip up newcomers. Names are case sensitive, so main, Main and MAIN are three different names and only the first one starts a program. And every name in the standard library lives inside the namespace std, so you write std::cout; the prefix says which library the name belongs to.
std::cout is the output stream. The << operator sends a value into it, and several sends can be chained on one line: std::cout << "Loans: " << 42 << '\n';. Writing '\n' starts a new line. std::endl also starts a new line but additionally flushes the output buffer, which is slower inside loops, so '\n' is the usual choice. std::cin is the matching input stream: std::cin >> n reads the next whitespace-separated token into n, and std::getline(std::cin, line) reads a whole line into a string.
Comments start with // and run to the end of the line, or sit between /* and */. The compiler discards them; they are there to say why the code does what it does.
Syntax
#include <iostream> // declarations for std::cout and std::cin
int main() { // execution starts here
statement; // each statement ends with a semicolon
statement;
return 0; // 0 reports success to the operating system
}Compile and run from a terminal with g++ -std=c++17 -Wall hello.cpp -o hello and then ./hello. -std=c++17 selects the language standard used in every lesson here; -Wall switches on the compiler's most useful warnings, which catch many mistakes for free.
The parts of the skeleton
| Part | What it does |
|---|---|
| #include <iostream> | Copies in the declarations of std::cout and std::cin so they can be used below |
| int main() | The function the operating system calls first; its int result is the exit status |
| { ... } | The block that forms the body of main |
| std::cout << value; | A statement that sends value to standard output |
| return 0; | Ends main and reports success; any other value means failure |
Printing three lines
Three ways to end a line, and a number sent to the stream alongside text.
#include <iostream>
int main() {
std::cout << "Welcome to the Riverside Library\n";
std::cout << "Opening hours: 9 to 17" << std::endl;
std::cout << "Books on loan: " << 42 << '\n';
return 0;
}Output
Welcome to the Riverside Library Opening hours: 9 to 17 Books on loan: 42
The first line puts the newline inside the string, the second uses std::endl, the third sends the single character '\n' after the number. All three end the line; only std::endl also forces the buffer to be written out immediately. The number 42 is not text, but << knows how to print an int, so it can be chained after a string without any conversion.
Reading input and echoing it back
A theatre booking desk reads a customer's full name, then a number of seats.
#include <iostream>
#include <string>
int main() {
std::string name;
int seats;
std::getline(std::cin, name);
std::cin >> seats;
std::cout << "Booking for " << name << "\n";
std::cout << "Seats reserved: " << seats << "\n";
return 0;
}Input given to the program: Priya Natarajan ↵ 3
Output
Booking for Priya Natarajan Seats reserved: 3
The name contains a space, so it is read with std::getline, which takes everything up to the end of the line. The seat count is read with >>, which skips whitespace and reads one token; the text "3" is converted into the int 3 automatically because seats was declared as an int. Declaring the variables with a type before reading into them is required in C++: the type tells >> what kind of value to parse.
Statements, blocks and comments
One statement spread over three lines, and a block with its own variable.
#include <iostream>
// A program is a list of statements; each one ends with a semicolon.
int main() {
int shelves = 4; // a declaration is a statement too
int perShelf = 30;
std::cout << "Capacity: "
<< shelves * perShelf // one statement spread over three lines
<< " books\n";
/* Braces group statements into a block. A variable declared
inside a block stops existing at its closing brace. */
{
int extra = 12;
std::cout << "With the trolley: " << shelves * perShelf + extra << "\n";
}
return 0;
}Output
Capacity: 120 books With the trolley: 132
The std::cout statement runs from std::cout to the semicolon after " books\n"; the line breaks in between change nothing. extra is declared inside the inner braces, so it can be used there and nowhere else; trying to print extra after the closing brace would be a compile error. Both comment styles are stripped out before compilation.
Common mistakes
Leaving out a semicolon
Why it goes wrong: The compiler only notices the missing semicolon when it reaches the next token that does not fit, so the error
expected ';' before ...often points at the line after the real problem.Fix: When an error mentions a missing semicolon, read the line above the one it names.
C++ · fixint shelves = 4 // error is reported on the next line std::cout << shelves;Using cout without std:: or without #include <iostream>
Why it goes wrong: Both produce
'cout' was not declared in this scope. The name lives in the std namespace, and the compiler only knows it exists once the header has been included.Fix: Add
#include <iostream>at the top and writestd::cout. Small programs sometimes addusing namespace std;instead; the lessons keep the prefix so the origin of every name stays visible.Declaring main as void main() or naming it Main
Why it goes wrong: The standard requires
mainto return int; g++ rejectsvoid main()with'::main' must return 'int'. A function calledMainis just an ordinary function, and the build fails at the link step withundefined reference to 'main'.Fix: Always write
int main()in lower case.C++ · fixint main() { return 0; }Writing statements outside any function
Why it goes wrong: Only declarations may appear at file level. A line such as
std::cout << "hi";outside main produces a compile error, because there is no function for it to execute in.Fix: Put every statement inside the body of main or another function.
Where you use this
A compiled C++ program is a self-contained executable, which is why the language is chosen for tools that must start fast and run without an interpreter present. Even with only this lesson you can build a small utility: a program that reads a delivery note from standard input and prints a formatted label. Once compiled, the executable runs as many times as you like on any input, with no compile step in between. The habit worth building now is to compile with -Wall every time and to treat each warning as something to fix; the compiler is the fastest reviewer you will ever have.
g++ -std=c++17 -Wall label.cpp -o label
./label < delivery-note.txtKey points
- Source code is compiled into an executable first; the executable is what runs.
- Execution begins in
int main(); reaching its end without a return statement returns 0. #include <iostream>gives youstd::coutandstd::cin;#include <string>gives youstd::string.- Every statement ends with a semicolon; braces group statements into blocks.
- Names are case sensitive, and standard library names are written with the
std::prefix. <<sends values tostd::coutand can be chained;>>reads tokens fromstd::cin;std::getlinereads a whole line.- Prefer
'\n'overstd::endlunless you need the output flushed at that moment.
Try it yourself
The program prints a fixed greeting. Change it so it reads the branch name from input with std::getline and prints Welcome to followed by that name.
#include <iostream>
#include <string>
int main() {
std::cout << "Welcome to the main branch\n";
return 0;
}
Harbour Street branchWelcome to Harbour Street branch#include <iostream>
#include <string>
int main() {
std::string branch;
std::getline(std::cin, branch);
std::cout << "Welcome to " << branch << "\n";
return 0;
}
Practise this
Exercises for this lesson are in the C++ practice set.
Related lessons
- Variables and Types in C++Declaring C++ variables with int, double, char, bool and std::string, initialising them, using const and auto, and why an uninitialised variable is a bug.9 min
- Operators in C++C++ arithmetic, comparison, logical and assignment operators: integer division and modulo, prefix versus postfix ++, short-circuit evaluation and precedence.9 min
Frequently asked questions
Do I have to write return 0; at the end of main?
No. main is the one function where reaching the closing brace counts as return 0;. Writing it out makes the intent visible, and returning a different value (1 by convention) tells the shell that the program failed. Every other function with a non-void return type must return a value on every path.
What is the difference between '\n' and std::endl?
Both end the current line. std::endl also flushes the output buffer, forcing the text to be written out immediately, which costs time when it happens thousands of times inside a loop. '\n' only appends the character and lets the stream flush when its buffer fills or when the program ends. Use '\n' by default.
Should I write using namespace std;?
It lets you write cout instead of std::cout by importing every name from the std namespace into your file. In a ten-line program that is harmless. In a larger program it invites clashes, because std contains ordinary-looking names such as count, distance and size. These lessons keep the std:: prefix so it is always clear where a name comes from.
How this page was checked. Every program on it was run with GCC 13 (C++17) at build time by the publishing checks, and the output shown is what it printed. Running C++ inside the browser is not available yet, so the Run button is absent rather than pretending; copy the code and run it with GCC 13 (C++17) locally.