C++ Introduction
C++ is a general-purpose, compiled programming language that gives you fine-grained control over how a computer executes your code and manages memory, while still supporting high-level features like classes and generic programming. It powers everything from operating systems and game engines to web browsers and financial trading systems. This lesson gives you a solid, complete foundation: what C++ is, how a C++ program actually runs on your machine, and how to write, read, and debug your first programs.
Overview: What Is C++ and How Does It Work?
C++ was created by Bjarne Stroustrup starting in 1979 as an extension of the C language, originally called “C with Classes.” It was designed to add object-oriented and other high-level features to C without sacrificing C’s speed and low-level control over hardware. Today C++ is standardized by the ISO committee, and the language has evolved through major revisions known as C++98, C++11, C++14, C++17, C++20, and C++23, each adding significant new capabilities while keeping the language largely backward compatible.
Two properties define how C++ behaves, and understanding them early will save you a lot of confusion later:
C++ is a compiled language. Unlike an interpreted language such as Python or JavaScript, where a program is read and executed line-by-line at runtime, a C++ program is first translated by a compiler (such as g++, clang++, or MSVC) into machine code — instructions your CPU can execute directly. This translation happens in stages: preprocessing, compilation to object code, and linking into a final executable file. Because the translation happens once, ahead of time, compiled C++ programs typically run much faster than interpreted code, but you must recompile after every change before you can run it again.
C++ is statically and strongly typed. Every variable has a fixed type (such as int, double, or std::string) that is checked at compile time, not at runtime. This means many mistakes — like trying to add a number to text incorrectly — are caught by the compiler before your program ever runs, rather than crashing unexpectedly for a user.
C++ is also a multi-paradigm language: you can write straightforward procedural code (functions and variables), object-oriented code (classes and objects), and generic code (templates that work with any type), often mixing all three in the same program. It also gives you direct control over memory through pointers and manual allocation, which is powerful but requires discipline — a theme you’ll see throughout this course.
Syntax: Anatomy of a C++ Program
Every C++ program follows a similar skeleton. Here is the general form:
#include <iostream>
using namespace std;
int main() {
// statements go here
return 0;
}
| Part | Meaning |
|---|---|
#include <iostream> |
A preprocessor directive that pulls in the standard input/output library, giving you access to cout and cin. |
using namespace std; |
Lets you write cout instead of std::cout. The standard library lives inside a namespace called std to avoid naming conflicts. |
int main() |
The entry point of every C++ program. Execution always begins here. The int means it returns an integer status code to the operating system. |
{ } |
Curly braces define a block — the body of a function, loop, or condition. |
; |
Every statement in C++ must end with a semicolon. |
return 0; |
Ends main() and reports success (0) to the operating system; any nonzero value conventionally signals an error. |
// and /* */ |
Comments. // comments out the rest of a line; /* ... */ comments out a block spanning multiple lines. Comments are ignored by the compiler. |
Examples
Example 1: Your First Program
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
cout << "Welcome to C++ programming." << endl;
return 0;
}
Output:
Hello, World!
Welcome to C++ programming.
The cout object (short for “character output”) sends data to the console using the << insertion operator. You can chain multiple values with << in a single statement, and endl inserts a newline and flushes the output buffer.
Example 2: Variables and Arithmetic
#include <iostream>
using namespace std;
int main() {
int apples = 5;
int oranges = 3;
int totalFruit = apples + oranges;
double pricePerApple = 0.50;
double totalCost = apples * pricePerApple;
cout << "Apples: " << apples << endl;
cout << "Oranges: " << oranges << endl;
cout << "Total fruit: " << totalFruit << endl;
cout << "Total cost of apples: $" << totalCost << endl;
return 0;
}
Output:
Apples: 5
Oranges: 3
Total fruit: 8
Total cost of apples: $2.5
This example declares variables of two different types: int for whole numbers and double for decimal numbers. Because C++ is statically typed, once apples is declared as an int, it can only ever hold whole numbers. Note that totalCost prints as 2.5, not 2.50 — by default, cout does not preserve trailing zeros.
Example 3: Multiple Data Types Together
#include <iostream>
#include <string>
using namespace std;
int main() {
string studentName = "Ava Thompson";
int age = 16;
double gpa = 3.85;
char grade = 'A';
bool isEnrolled = true;
cout << "Student Report" << endl;
cout << "---------------" << endl;
cout << "Name: " << studentName << endl;
cout << "Age: " << age << endl;
cout << "GPA: " << gpa << endl;
cout << "Letter Grade: " << grade << endl;
cout << "Enrolled: " << boolalpha << isEnrolled << endl;
return 0;
}
Output:
Student Report
---------------
Name: Ava Thompson
Age: 16
GPA: 3.85
Letter Grade: A
Enrolled: true
This program mixes five fundamental types: string (text, requires #include <string>), int, double, char (a single character in single quotes), and bool (true or false). The boolalpha stream manipulator tells cout to print true/false as words instead of the default 1/0.
Under the Hood: From Source Code to Running Program
When you run a command like g++ hello.cpp -o hello, several distinct stages happen before you get a runnable program:
- Preprocessing: Lines starting with
#, like#include, are processed first.#include <iostream>literally copies the contents of the iostream header into your file before compilation begins. - Compilation: The compiler translates your C++ source code into assembly, then into machine-specific object code (a
.ofile), checking your syntax and types along the way. This is where most beginner errors, like a missing semicolon or a type mismatch, are caught. - Linking: The linker combines your object code with the compiled code of any libraries you used (like the standard library’s implementation of
cout) into a single executable file. - Execution: The operating system loads the executable into memory and begins executing instructions starting at
main(). Local variables are placed on the stack, a region of memory that grows and shrinks automatically as functions are entered and exited.
This is fundamentally different from an interpreted language, where a separate program (the interpreter) reads and executes your source code every time you run it, with no separate machine-code file produced.
Common Mistakes
Mistake 1: Forgetting a semicolon. Writing cout << "Hi" << endl without a trailing semicolon produces a compiler error, often pointing at the next line rather than the actual missing one. Every statement needs to end with ;.
Mistake 2: Using cout without including <iostream> or the std namespace. If you write cout << "Hi"; without either #include <iostream> or using namespace std; (or writing std::cout explicitly), the compiler reports that cout was not declared. Beginners often only add one of the two required pieces and are confused why it still fails. The fix is to always pair the header include with either the using namespace std; line or the std:: prefix on every standard library name you use.
Mistake 3: Confusing = with ==. A single = assigns a value; a double == compares two values for equality. Writing if (age = 18) instead of if (age == 18) is a classic bug: it silently assigns 18 to age and the condition is always true, rather than actually comparing. Always double-check comparison operators inside if statements.
Mistake 4: Mismatching data types. Storing a decimal value like 3.99 into an int variable silently truncates it to 3 instead of rounding — no error is raised. Use double or float whenever fractional precision matters, and use int only for whole numbers.
Best Practices
- Always include the headers you actually use (
<iostream>for I/O,<string>for text, etc.) rather than relying on them being pulled in indirectly by another header. - Prefer explicit
std::coutover a blanketusing namespace std;in larger, real-world projects to avoid naming collisions; for short learning examples,using namespace std;is fine and keeps code readable. - Give variables descriptive names (
totalCost, nottc) — the compiler doesn’t care, but future-you will. - Compile often. Don’t write 100 lines and compile once; compile after every small change so errors are easy to trace to their source.
- Read compiler error messages from the top down — the first error listed is often the real cause; later errors can be side effects of it.
- Always end
main()withreturn 0;for clarity, even though C++11 and later implicitly return 0 if you omit it.
Practice Exercises
Exercise 1: Write a program that declares three int variables representing the price of three items, prints each price, and prints their total.
Exercise 2: Write a program with a string variable holding your favorite programming language and an int variable holding how many years you’ve been learning to code. Print both in a single sentence using cout.
Exercise 3: Predict the output of this code before running it, then verify: int x = 7; double y = x / 2; followed by cout << y;. (Hint: think carefully about what type the division x / 2 produces before it is assigned to y.)
Summary
- C++ is a compiled, statically-typed, multi-paradigm language created by Bjarne Stroustrup as an extension of C.
- Compiled means your source code is translated ahead of time (preprocessing → compilation → linking) into a machine-code executable, rather than interpreted line by line at runtime.
- Every program starts execution at
int main(), and every statement ends with a semicolon. #includepulls in library code you need, such as<iostream>forcoutandcin.- Common data types include
int,double,char,bool, andstring, each with a fixed, compiler-checked type. - Watch out for missing semicolons, missing includes/namespace qualifiers, confusing
=with==, and silent type truncation — these are the most common beginner errors.
