Beginner · First steps: compiling, output, variables and input · topic 2 of 42 · 20 min
Your first program: main, cout and namespaces
Explanation
The smallest useful program
#include <iostream>
int main() {
std::cout << "Namaste, C++!\n";
return 0;
}Let us read it line by line.
- #include <iostream> brings in the input/output part of the standard library. The standard library is the large set of ready-made code that comes with every C++ compiler.
- int main() starts the main function. A function is a named block of code. The operating system calls main when the program starts. int means main gives back a whole number.
- The curly braces { } mark the body of main: the statements that run, top to bottom.
- std::cout is the "character output" stream: text sent to it appears in the terminal. << means "send this into the stream".
- "\n" is the newline character: it moves the cursor to the next line.
- return 0; ends main and tells the operating system the program finished without error. Any other number usually means an error. (In main only, you may leave this line out; the compiler then returns 0 for you.)
- Every statement ends with a semicolon ;. Forgetting it is the most common beginner error.
Chaining output
#include <iostream>
int main() {
std::cout << "Train: " << 12951 << '\n';
std::cout << "Fare: Rs " << 1450.50 << '\n';
std::cout << 7 + 5 << '\n';
}You can chain many << in one statement. Text in double quotes is a string; numbers are printed as numbers, and expressions like 7 + 5 are calculated first. A single character uses single quotes, like '\n'.
std::endl versus '\n'
std::endl also ends the line, but it additionally flushes the stream: it forces the text out to the screen immediately. Flushing is slow when you print many lines, so prefer '\n' and use std::endl only when you really need the text shown at once (for example just before a long calculation).
Namespaces and std::
A namespace is a named group of names, so two libraries can both have something called "count" without a clash. Everything in the standard library lives in the namespace std. std::cout means "the cout that belongs to std". :: is called the scope resolution operator.
#include <iostream>
using namespace std; // fine in tiny practice files, avoid in real projects
int main() {
cout << "No std:: needed here\n";
}Comments
// A comment until the end of the line
/* A comment that can
span many lines */
int main() { }Reading compiler errors
Compiler messages look scary but always give a file name and line number, like hello.cpp:4:40: error: expected ';' before '}' token. Fix the FIRST error first; later errors are often caused by the first one. A missing semicolon is often reported on the next line.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Your first program: main, cout and namespaces · 1/6
Let us write your first real C++ program.
Prefer a video by a teacher? Find free videos on “c++ hello world main cout explained beginners” on YouTube ↗
In real life: A railway ticket printout
Ticket machines at stations print a short summary: train number, class and fare. Under the hood the program sends text and numbers to an output stream, just like std::cout, only the stream goes to a printer instead of a screen.
#include <iostream>
int main() {
std::cout << "PNR: 4521337890\n";
std::cout << "Train 12951, Class 3A\n";
std::cout << "Fare: Rs " << 2150 << '\n';
}Practice (0/3 done)
What does this print? std::cout << "Sum: " << 4 + 6 << '\n';
Which line has the bug? 1: #include <iostream> 2: int main() { 3: std::cout << "Hi" 4: }
Write a program that prints a small shop bill on four lines: the shop name, two items with prices, and the total (calculated with + in the code, not typed by hand).
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Variables, types and constantsFirst steps: compiling, output, variables and input · same module
- Reading input and formatting outputFirst steps: compiling, output, variables and input · same module
- The structure of a C programC Programming (from zero to systems) · Getting started with C
- std::optional, std::variant and std::string_viewModern C++: lambdas, C++17 and C++20 essentials
- Your first program: output, input and the Main methodC# and .NET · Getting started with C# and .NET
- Text: C strings and std::stringReferences, pointers, arrays and strings
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Where does a C++ program start running?
Answer: In the function main
The operating system calls main when the program starts.
What does std:: in std::cout mean?
Answer: cout comes from the std namespace
std is the namespace of the standard library and :: picks a name from it.
Why is '\n' usually preferred over std::endl?
Answer: '\n' does not flush the stream, so it is faster
std::endl ends the line and flushes the output, which costs time when printing many lines.
Where should you never write using namespace std;?
Answer: In a header file
In a header it leaks into every file that includes the header and can cause name clashes.
What does return 0; at the end of main mean?
Answer: The program finished successfully
The value returned from main is the exit code. 0 means success.
std::cout << std::setw(5) << 42; prints…Related
Answer: 42 (3 spaces then 42)
setw(5) pads the next value to 5 characters, on the left by default.
Where does every C program start executing?Related
Why is std::string_view a good parameter type for read-only text?Related
Answer: It accepts std::string, literals and substrings without copying
A view is just a pointer and a length.
What ends a statement in C#?Related
Answer: A semicolon ;
Every C# statement ends with a semicolon.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “First steps: compiling, output, variables and input” before its exam: Variables, types and constants, Reading input and formatting output.
- Module 1 exam: First steps · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Decisions, loops and functions. 42 topics left in the course before the final exam.