Your First C++ Program

C++ · Lesson 3 of 32 7 min read Updated

Now that your compiler works, it is time to write a real program and understand every line of it. You will learn the structure every C++ program shares, two ways to print output (the modern std::println from C++23 and the classic std::cout), how to write comments, and how to read the compiler's error messages without panic.

The structure of a C++ program

Create a file called welcome.cpp and type this program. Type it rather than copy it: your fingers learn the syntax faster that way.

C++
// welcome.cpp: my first C++ program
#include <print>

int main() {
    std::println("Welcome to C++, Priya!");
    std::println("Today we learn to print.");
    return 0;
}
Output
Welcome to C++, Priya!
Today we learn to print.

Line by line:

  • // welcome.cpp ... is a comment. The compiler ignores everything after // on that line.
  • #include <print> tells the preprocessor to bring in the standard library header that declares std::println. A header is a file of declarations you can reuse.
  • int main() defines the main function. Every C++ program starts running at the first line inside main. The int means main returns a whole number to the operating system.
  • The curly braces { and } mark the start and end of the function body.
  • std::println("..."); is a statement that prints text and then a newline. std is the namespace of the standard library, and :: means "the name inside". Every statement ends with a semicolon.
  • return 0; tells the operating system the program finished successfully. In main only, you may leave it out; the compiler then behaves as if you wrote return 0;.

Compile and run it as you learned in Install a Compiler & VS Code:

Terminal
g++ -std=c++23 -Wall -Wextra welcome.cpp -o welcome
./welcome

C++23 gives you two printing functions in <print>:

  • std::println prints and then moves to a new line.
  • std::print prints and stays on the same line.

Both understand placeholders. Each {} in the text is replaced by the next value you pass. You can also number the placeholders, starting from 0, to choose the order yourself.

C++
#include <print>

int main() {
    std::print("Train 12015 ");
    std::print("leaves at ");
    std::println("{}:{} am", 6, 10);
    std::println("Fare for {} seats: Rs. {}", 3, 3 * 450);
    std::println("{1} comes before {0}", "second", "first");
}
Output
Train 12015 leaves at 6:10 am
Fare for 3 seats: Rs. 1350
first comes before second

The two std::print calls do not add newlines, so the first three calls build one line together. In the last line, {1} takes the second value and {0} the first. You will learn many more formatting options, such as decimal places and alignment, in Strings, string_view & format.

The classic way: std::cout

Before C++23, every C++ program printed with std::cout (pronounced "see-out", short for character output) from the <iostream> header. You will see it in almost all existing code, books and exam papers, so you must be able to read it.

C++
#include <iostream>

int main() {
    int seats = 3;
    std::cout << "Fare for " << seats << " seats: Rs. " << seats * 450 << '\n';
    std::cout << "Have a safe journey!" << std::endl;
}
Output
Fare for 3 seats: Rs. 1350
Have a safe journey!

The << operator sends each piece to the output, one after another. '\n' is the newline character. std::endl also prints a newline but then flushes the output (forces it to be written immediately), which is slower when you print many lines. Prefer '\n'.

Comments and special characters

C++ has two kinds of comments. Use them to explain why code does something, not to repeat what it obviously does.

C++
#include <print>

/* A block comment can span
   several lines. */
int main() {
    std::println("Name:\tRohan");           // \t inserts a tab
    std::println("He said \"Well played!\""); // \" prints a double quote
    std::println("Path: C:\\cpp\\notes");     // \\ prints one backslash
    std::println("Set {{1, 2, 3}} has {} items", 3);
}
Output
Name:	Rohan
He said "Well played!"
Path: C:\cpp\notes
Set {1, 2, 3} has 3 items

A backslash starts an escape sequence: \n (newline), \t (tab), \" (double quote) and \\ (backslash). Inside std::println text, curly braces are special, so you write {{ and }} to print a literal { or }.

Reading compiler errors

Everyone makes typing mistakes. Here a semicolon is missing at the end of the first statement:

C++
#include <print>

int main() {
    std::println("Score: {}", 42)
    std::println("Done");
}

GCC stops and prints an error similar to this:

Output
error.cpp: In function 'int main()':
error.cpp:4:34: error: expected ';' before 'std'

The message gives the file name, the line number (4) and the column (34), then describes the problem. Go to that line and look at the end of it. Two tips: always fix the first error first, because one mistake can cause several later messages, and read the line just before the reported one as well.

Common mistakes

  • Missing semicolons. Every statement ends with ;. The error often points to the next line.
  • Wrong capital letters. C++ is case-sensitive: Main, STD::println and std::PrintLn are all errors.
  • Forgetting the header. Using std::println without #include <print> gives an error such as "'println' is not a member of 'std'".
  • Single quotes for text. 'Hello' is wrong; text uses double quotes "Hello". Single quotes hold exactly one character, such as 'A'.

Key points

  • Every program has an int main() function where execution starts; statements end with ;.
  • #include brings in standard library headers such as <print> and <iostream>.
  • std::println prints with a newline, std::print without; {} placeholders are filled with values.
  • std::cout << ... << '\n' is the classic way to print and is still everywhere in existing code.
  • Use // and /* */ for comments, \n, \t, \" and \\ for special characters, and {{ }} for literal braces in std::println.
  • Read compiler errors from the first one, using the line and column numbers.

Exercise

Write a program that prints a small cricket scorecard for Ananya: her name on the first line, then Runs: 58 and Balls: 41 on separate lines using placeholders, and finally a line Strike rate is runs * 100 / balls exactly as written. Then rewrite the first two lines using std::cout.

Show solution
C++
#include <iostream>
#include <print>

int main() {
    std::println("Player: {}", "Ananya");
    std::println("Runs: {}", 58);
    std::println("Balls: {}", 41);
    std::println("Strike rate is runs * 100 / balls");

    std::cout << "Player: " << "Ananya" << '\n';
    std::cout << "Runs: " << 58 << '\n';
}
Output
Player: Ananya
Runs: 58
Balls: 41
Strike rate is runs * 100 / balls
Player: Ananya
Runs: 58

The text inside quotes is printed exactly, so the * and / in the last std::println line are just characters, not maths.

Quick Quiz

1. Where does a C++ program start running?

2. What is the difference between std::print and std::println?

3. What does std::println("{1}-{0}", "a", "b"); print?

4. Why is '\n' usually preferred over std::endl?

Learn C++ with a mentor

Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call