SovranCode
Modern C++ Lesson 03
Course contents50 available · 0 planned

Get a program running

01 · C++ Introduction: What Is C++?02 · How to Install a C++ Compiler and Set Up Your Editor03 · C++ Hello World: Your First Program Explained04 · How to Compile and Run C++ Programs05 · C++ Debugging: Warnings and Breakpoints

Work with values and input

06 · C++ Variables: Initialization and Scope07 · C++ Data Types: int, double and Type Conversion08 · C++ const, constexpr and auto Explained09 · C++ Operators: Arithmetic, Comparison and Logic10 · C++ User Input: cin, getline and Validation

Control flow and functions

11 · C++ Conditions: if, else if and else12 · C++ Switch Statement: Cases, break and default13 · C++ For Loop: Syntax and Examples14 · C++ While and Do-While Loops: Examples15 · C++ Functions: Parameters and Return Values

Strings and sequences

16 · C++ Strings: std::string with Examples17 · C++ Vector: std::vector with Examples18 · C++ Arrays: std::array and Bounds Checking19 · C++ Range-Based For Loop and Iterators20 · C++ Vector Practice: Build a Data Summary

Model data with classes

21 · C++ Structs and enum class Explained22 · C++ Classes and Objects: Encapsulation23 · C++ Constructors and Member Initialization24 · C++ Const Member Functions and Composition25 · C++ Copying Objects and the Rule of Zero

Lifetime and resource ownership

26 · C++ Object Lifetime, Destructors and RAII27 · C++ Pointers and References: nullptr and Borrowing28 · C++ unique_ptr: Smart Pointers and Ownership29 · C++ Move Semantics: std::move vs Copying30 · C++ string_view and span: Avoid Dangling Views

Containers and algorithms

31 · C++ map vs unordered_map: Lookup and Examples32 · C++ set, queue and stack: When to Use Each33 · C++ Lambda Expressions and STL Algorithms34 · C++ sort and binary_search: Rules and Complexity35 · C++20 Ranges: Views, filter and transform

Errors, files, and interfaces

36 · C++ optional and variant Explained37 · C++ Exceptions: try, catch and Safe Cleanup38 · C++ File Handling: Read and Write Text Files39 · C++ Input Parsing and Data Validation40 · C++ Polymorphism: Virtual Functions and Interfaces

Generic programming and quality

41 · C++ Templates: Function and Class Examples42 · C++20 Concepts and Template Constraints43 · C++ Unit Testing: Normal and Boundary Cases44 · C++ Sanitizers: Find Memory and Undefined Behavior Bugs45 · C++ Performance: Benchmark Before Optimizing

Build and deliver a complete application

46 · C++ Header Files and Translation Units47 · C++ CMake Tutorial: Build an Executable48 · C++ Dependencies and CTest: Automated Tests49 · C++ Multithreading: Threads and Data Races50 · C++ Command-Line Applications: Help and Release Checks
Modern C++50 available · 0 planned

Get a program running

01 · C++ Introduction: What Is C++?02 · How to Install a C++ Compiler and Set Up Your Editor03 · C++ Hello World: Your First Program Explained04 · How to Compile and Run C++ Programs05 · C++ Debugging: Warnings and Breakpoints

Work with values and input

06 · C++ Variables: Initialization and Scope07 · C++ Data Types: int, double and Type Conversion08 · C++ const, constexpr and auto Explained09 · C++ Operators: Arithmetic, Comparison and Logic10 · C++ User Input: cin, getline and Validation

Control flow and functions

11 · C++ Conditions: if, else if and else12 · C++ Switch Statement: Cases, break and default13 · C++ For Loop: Syntax and Examples14 · C++ While and Do-While Loops: Examples15 · C++ Functions: Parameters and Return Values

Strings and sequences

16 · C++ Strings: std::string with Examples17 · C++ Vector: std::vector with Examples18 · C++ Arrays: std::array and Bounds Checking19 · C++ Range-Based For Loop and Iterators20 · C++ Vector Practice: Build a Data Summary

Model data with classes

21 · C++ Structs and enum class Explained22 · C++ Classes and Objects: Encapsulation23 · C++ Constructors and Member Initialization24 · C++ Const Member Functions and Composition25 · C++ Copying Objects and the Rule of Zero

Lifetime and resource ownership

26 · C++ Object Lifetime, Destructors and RAII27 · C++ Pointers and References: nullptr and Borrowing28 · C++ unique_ptr: Smart Pointers and Ownership29 · C++ Move Semantics: std::move vs Copying30 · C++ string_view and span: Avoid Dangling Views

Containers and algorithms

31 · C++ map vs unordered_map: Lookup and Examples32 · C++ set, queue and stack: When to Use Each33 · C++ Lambda Expressions and STL Algorithms34 · C++ sort and binary_search: Rules and Complexity35 · C++20 Ranges: Views, filter and transform

Errors, files, and interfaces

36 · C++ optional and variant Explained37 · C++ Exceptions: try, catch and Safe Cleanup38 · C++ File Handling: Read and Write Text Files39 · C++ Input Parsing and Data Validation40 · C++ Polymorphism: Virtual Functions and Interfaces

Generic programming and quality

41 · C++ Templates: Function and Class Examples42 · C++20 Concepts and Template Constraints43 · C++ Unit Testing: Normal and Boundary Cases44 · C++ Sanitizers: Find Memory and Undefined Behavior Bugs45 · C++ Performance: Benchmark Before Optimizing

Build and deliver a complete application

46 · C++ Header Files and Translation Units47 · C++ CMake Tutorial: Build an Executable48 · C++ Dependencies and CTest: Automated Tests49 · C++ Multithreading: Threads and Data Races50 · C++ Command-Line Applications: Help and Release Checks
PREVIOUS LESSONHow to Install a C++ Compiler and Set Up Your Editor
NEXT LESSONHow to Compile and Run C++ Programs
C++ foundations · Lesson 03 About 40 min with practice

C++ Hello World: Your First Program Explained

Write C++ Hello World, understand main, headers and cout, predict output, fix a syntax error, and build a three-line console introduction.

Before you begin

Understand the build loop. A local compiler is useful but not required for the runnable greeting exercises.

What you will learn

  • Explain headers and the main function in a hosted program.
  • Distinguish statements, braces and semicolons.
  • Use std::cout with literals and initialized values.
  • Predict spaces and line breaks precisely.
  • Repair syntax without changing unrelated behavior.

Start with one observable promise

Hello World is deliberately small. Its job is not to demonstrate every language feature; it gives you a complete path from source to visible behavior. Our contract is one line containing Hello, C++!, followed by a newline, and successful completion. Writing that expectation before running makes it possible to tell whether the program did the intended work rather than merely produced some text.

The exact spelling matters because output is an interface. An extra space, missing punctuation or missing newline may matter to a user, a script or a test. Do not treat this precision as memorizing magic syntax. You are learning how explicit instructions produce explicit observations. Later programs will have richer interfaces, but they still benefit from a small, testable promise.

Annotated Hello World: include requests stream declarations, main is the entry function, braces group its body, cout inserts text, semicolons end statements, and return zero communicates successful completion.
Read the structure from the outside inward, then trace the statements in execution order.
C++ PRACTICE RUNNER

Hello World, one line at a time

Run once, then change only the greeting. Predict punctuation and the final newline before running again.

#include <iostream>

int main() {
    std::cout << "Hello, C++!\n";
    return 0;
}
TERMINAL OUTPUT
Predict the output, edit the source, then select Run code.

C++20 compiler runner: source and input are sent only when you press Run to this website's execution endpoint, not an external vendor. Local preview requires Docker and gcc:14; production requires a separately isolated execution service. Network is disabled; execution is limited to 3 seconds, compilation to 10 seconds, memory to 384 MB and output to 32 KB. Single-file programs only. Don't enter secrets. Edits reset on refresh; Copy your work to keep it.

Compare with the starter's expected output
Hello, C++!

After editing inputs, calculate a new prediction; this reference describes only the starter.

Headers provide declarations; main starts execution

The #include <iostream> directive requests the declarations for stream facilities used below. It is processed as part of preparing the source, not executed as a line of your program at runtime. A header is not a downloaded library package, and including it does not call every operation it declares. Here it allows the compiler to understand the standard output facility you name.

In this ordinary hosted program, int main() names the entry function. The parentheses belong to the function declaration; the braces enclose its body. int describes the result communicated when the function completes. For this first program we write return 0 explicitly to show successful completion. Reaching the end of main also has a special successful-return rule, but writing the statement now makes the control flow visible.

The source is read and checked as a whole during a build, while runtime follows the program's control flow. Do not confuse the order in which the compiler sees declarations with the order in which operations happen. In this simple body the output statement precedes return, so the greeting is produced first. Later functions and branches make execution order more interesting without changing that distinction.

Statements are not the same as lines

A semicolon ends the output statement and the return statement. Braces delimit the function body. A physical newline in the source helps a reader, but it usually does not terminate a C++ statement. You can split a long output statement across several source lines and still end it with one semicolon. Conversely, putting two statements on one line does not merge them into one operation.

Use indentation to reveal structure rather than relying on it to create structure. The compiler follows punctuation and language rules. A missing semicolon may cause a message on the next line because that is where the parser discovers the previous statement cannot continue. Read the nearby preceding statement before making a random change at the highlighted location. One carefully placed repair is better than several edits that hide the cause.

Comments document intent and are ignored as program instructions. A // comment ends at the source line boundary; a /* ... */ comment spans its delimiters. Explain a reason or non-obvious assumption rather than repeating the obvious meaning of cout. Never place a missing semicolon inside a comment and expect it to count as syntax. Clear layout and focused comments make diagnostics easier to investigate.

Separate text, values and output operations

std::cout names the standard output stream. The std:: qualifier identifies the standard namespace rather than a local variable with a similar name. The << operations insert values into that stream. In this lesson we keep the qualifier visible so you can see where each library facility comes from. It is not necessary to introduce a global using directive merely to make a tiny example shorter.

Double quotes surround a string literal: the text is part of the source instruction. A std::string object can hold text as a named value, while an int object can hold a count. Outputting a variable prints its current value, not its identifier. If you want the word Sessions in a report, write that label as text; if you want the number three, insert the integer value. Keeping the label and data separate makes changes predictable.

The escape sequence \n represents a newline in a literal. It is not the same as moving to another source line. The character literal '\n' and a string literal containing a newline are both suitable for these output examples. std::endl also requests flushing the stream, which is a separate concern; this course uses newline characters where only a line break is needed. Do not infer advanced performance rules from such a tiny program.

C++ PRACTICE RUNNER

A greeting with named values

Change learner and sessions independently. Explain which output lines change and why.

#include <iostream>
#include <string>
int main() {
    const std::string learner{"Alex"};
    const int sessions{3};
    std::cout << "Learner: " << learner << '\n';
    std::cout << "Sessions: " << sessions << '\n';
    return 0;
}
TERMINAL OUTPUT
Predict the output, edit the source, then select Run code.

C++20 compiler runner: source and input are sent only when you press Run to this website's execution endpoint, not an external vendor. Local preview requires Docker and gcc:14; production requires a separately isolated execution service. Network is disabled; execution is limited to 3 seconds, compilation to 10 seconds, memory to 384 MB and output to 32 KB. Single-file programs only. Don't enter secrets. Edits reset on refresh; Copy your work to keep it.

Compare with the starter's expected output
Learner: Alex
Sessions: 3

After editing inputs, calculate a new prediction; this reference describes only the starter.

Trace exact output before changing the source

For the first report line, follow each insertion: the label includes a colon and a space, learner supplies Alex, and the final character ends the line. For the next line, the count is formatted as visible digits. This example does not ask for input or save a profile. Its values are fixed in the source. A browser output panel is a teaching aid, not proof that a database or account system exists.

Try removing the space after the colon, then predict the result. Try removing the first newline and observe that the second label follows on the same output line. Restore the starter before the next independent experiment. Changing one cause at a time lets you connect a visible difference to a particular source change. If the output surprises you, compare the literal characters before blaming the toolchain.

C++ PRACTICE RUNNER

Repair the missing statement boundary

This starter intentionally fails. Add the one missing semicolon; do not change the greeting or return value.

#include <iostream>

int main() {
    std::cout << "Hello, C++!\n"
    return 0;
}
TERMINAL OUTPUT
Predict the output, edit the source, then select Run code.

C++20 compiler runner: source and input are sent only when you press Run to this website's execution endpoint, not an external vendor. Local preview requires Docker and gcc:14; production requires a separately isolated execution service. Network is disabled; execution is limited to 3 seconds, compilation to 10 seconds, memory to 384 MB and output to 32 KB. Single-file programs only. Don't enter secrets. Edits reset on refresh; Copy your work to keep it.

Recognize three different kinds of mistake

A syntax error prevents this source from being built. A logic error can produce incorrect output despite a successful build. An environment error can prevent launching a valid executable. The same symptom—'it does not work'—therefore needs different evidence. Record the command, diagnostic and observed output instead of collapsing all three categories into a guess about C++ being difficult.

The browser interpreter accepts only the documented beginner subset. Its helpful messages are not the exact diagnostics emitted by GCC, Clang or MSVC. Verify local builds when you need compiler-specific behavior. In particular, a unsupported feature message does not mean the feature is invalid C++; it may simply be outside this practice tool. You should be able to describe both the program and the tool's limitation.

  • Missing semicolon → syntax repair.
  • Wrong wording with a successful run → check the output contract.
  • Edited source but unchanged local output → verify save, rebuild and executable path.
APPLY THE CONCEPT

Independent lab

Write a three-line learning introduction with a named learner, topic and session count. Define the exact output before editing.

Acceptance checklist

  • Include iostream and string for the library facilities you use.
  • Initialize a std::string learner, std::string topic and int sessions.
  • Print one labeled value on each line, with a final newline.
  • Use no interactive input or account information; choose fictional sample values.
  • Change sessions from 2 to 0 and verify that only the count line changes.
Need a hint?
  1. Use a separate cout statement for each line while learning the structure.
  2. Spaces inside labels are data; indentation outside literals is formatting.
  3. Copy the pattern of braces and statement terminators, not unexplained extra code.
C++ PRACTICE RUNNER

Write and run your lab

Build your own solution before revealing the reference. Use the input field for normal, boundary and invalid cases; this runner executes your program but does not grade it.

#include <iostream>
#include <string>
#include <sstream>
#include <limits>

int main() {
    // Implement the acceptance checklist above.
    return 0;
}

TERMINAL OUTPUT
Predict the output, edit the source, then select Run code.

C++20 compiler runner: source and input are sent only when you press Run to this website's execution endpoint, not an external vendor. Local preview requires Docker and gcc:14; production requires a separately isolated execution service. Network is disabled; execution is limited to 3 seconds, compilation to 10 seconds, memory to 384 MB and output to 32 KB. Single-file programs only. Don't enter secrets. Edits reset on refresh; Copy your work to keep it.

Your lab evidence and notes

Record predictions, actual output, commands and the cause of each repair. Code is plain text: this scratchpad does not execute or grade C++.

Loading local notes…

Review your acceptance checklist and quiz explanations before marking this lesson complete. This is self-review, not a grade or certification.

Reveal the explained lab solution
C++ PRACTICE RUNNER

Reference lab solution

Compare the reference with your own reasoning. Running this solution does not grade or complete the lesson.

#include <iostream>
#include <string>
int main() {
    const std::string learner{"Sam"};
    const std::string topic{"C++"};
    const int sessions{2};
    std::cout << "Learner: " << learner << '\n';
    std::cout << "Topic: " << topic << '\n';
    std::cout << "Sessions: " << sessions << '\n';
    return 0;
}
TERMINAL OUTPUT
Predict the output, edit the source, then select Run code.

C++20 compiler runner: source and input are sent only when you press Run to this website's execution endpoint, not an external vendor. Local preview requires Docker and gcc:14; production requires a separately isolated execution service. Network is disabled; execution is limited to 3 seconds, compilation to 10 seconds, memory to 384 MB and output to 32 KB. Single-file programs only. Don't enter secrets. Edits reset on refresh; Copy your work to keep it.

Expected output

Learner: Sam
Topic: C++
Sessions: 2

The headers declare the stream and string facilities. Each named object is initialized before its value is read.

The labels supply wording; the inserted variables supply data. Newlines keep the three reports separate.

With sessions initialized to zero, the third line becomes Sessions: 0. Zero is a meaningful count here, not an error or missing value.

Review before moving on

Explain the lesson's objectives in your own words, compare your lab evidence with the acceptance checklist, and keep the first failing case alongside your repair. Completing a page is not proof that every C++ feature or input is supported.

  • Explain headers and the main function in a hosted program.
  • Distinguish statements, braces and semicolons.
  • Use std::cout with literals and initialized values.
  • Predict spaces and line breaks precisely.
  • Repair syntax without changing unrelated behavior.

References and further reading

Original examples and exercises accompany these primary references. Tool-specific diagnostics and support depend on your installed version.

  • Microsoft: compile a native C++ program
  • C++ draft: main function
  • C++ draft: standard stream objects
KNOWLEDGE CHECK

Check your understanding

Answer all five questions, then review the explanations. Answers are not saved or synced; completion is a separate self-review choice.

01Which part names the entry function in this hosted example?
02What ends the cout statement?
03What does cout << sessions print when sessions contains 3?
04Why does the literal contain \n?
05The build succeeds but the label is wrong. What kind of issue is this?
PREVIOUS LESSONHow to Install a C++ Compiler and Set Up Your Editor
NEXT LESSONHow to Compile and Run C++ Programs
ON THIS PAGELearning objectivesStart with one observable promiseHeaders provide declarations; main starts executionStatements are not the same as linesSeparate text, values and output operationsTrace exact output before changing the sourceRecognize three different kinds of mistakeIndependent labReviewKnowledge checkReferences
Course overview