Chapter 01

Basics

Introduction to C++, its history, setting up your environment, and writing your first program

What You Will Learn

  • What C++ is and its role in software development
  • The history and evolution of C++
  • Why C++ remains relevant today
  • How to set up a development environment
  • How to write, compile, and run your first C++ program
  • The structure and components of a C++ program
  • How to use namespaces and comments
  • Best practices for code formatting and style

What is C++

C++ is a general-purpose, compiled programming language that supports multiple programming paradigms including procedural, object-oriented, and generic programming. It was designed to be efficient and flexible, giving programmers control over system resources while providing high-level abstractions.

C++ is known as a "middle-level" language because it combines features of both high-level languages (like Python or Java) and low-level languages (like C or Assembly). This means you can write abstract, readable code while still having the ability to directly manipulate hardware and memory when needed.

Key Characteristics

  • Compiled: C++ code is compiled directly to machine code, resulting in fast execution
  • Statically Typed: Variable types are checked at compile time, catching errors early
  • Multi-paradigm: Supports procedural, object-oriented, and generic programming
  • System-level Access: Direct memory manipulation through pointers
  • Zero-overhead Abstractions: High-level features don't sacrifice performance
  • Standard Library: Rich set of containers, algorithms, and utilities (STL)

Where C++ is Used

C++ is used in domains where performance, efficiency, and control over hardware are critical:

  • Operating Systems: Windows, macOS, Linux kernel modules, and device drivers
  • Game Development: Unreal Engine, Unity (core), CryEngine, and most AAA game titles
  • Web Browsers: Chrome, Firefox, Safari, and Edge are written in C++
  • Databases: MySQL, PostgreSQL, MongoDB, and Redis
  • Embedded Systems: Automotive software, IoT devices, robotics, and medical devices
  • Financial Systems: High-frequency trading platforms and banking software
  • Graphics and Visualization: Photoshop, Illustrator, Blender, and Maya
  • Machine Learning: TensorFlow, PyTorch (backend), and ONNX Runtime
  • Compilers and Tools: GCC, Clang, LLVM, and many IDEs

History of C++

Understanding C++'s history helps you appreciate why the language is designed the way it is.

Origins (1979-1983)

C++ was created by Bjarne Stroustrup at Bell Labs in Murray Hill, New Jersey. In 1979, Stroustrup began working on "C with Classes," which added object-oriented features to C. The goal was to combine the efficiency and flexibility of C with the organizational benefits of Simula's classes.

The Name "C++" (1983)

In 1983, the language was renamed to C++. The "++" is the increment operator in C, symbolizing that C++ is an enhanced ("incremented") version of C. Rick Mascitti is credited with coining the name.

Standardization

Standard Year Key Features
C++98 1998 First ISO standard, STL, templates, exceptions
C++03 2003 Bug fixes and clarifications
C++11 2011 auto, lambdas, move semantics, smart pointers, range-for
C++14 2014 Generic lambdas, relaxed constexpr, binary literals
C++17 2017 Structured bindings, if-init, std::optional, filesystem
C++20 2020 Concepts, ranges, coroutines, modules, three-way comparison
C++23 2023 std::expected, deducing this, more constexpr

C++11 is often called "Modern C++" because it introduced fundamental changes to how C++ is written. This guide focuses on Modern C++ (C++17 and later) practices.

Why Learn C++

Despite being over 40 years old, C++ remains one of the most important programming languages. Here's why you should learn it:

Performance

C++ produces highly optimized machine code. When milliseconds matter (gaming, trading, real-time systems), C++ is often the only choice. Unlike garbage-collected languages, C++ gives you deterministic memory management.

Industry Demand

C++ developers are in high demand across multiple industries. Major tech companies (Google, Microsoft, Apple, Meta, Amazon) use C++ extensively. Game studios, financial institutions, and embedded systems companies actively hire C++ developers.

Understanding Computers

Learning C++ teaches you how computers actually work. You'll understand memory layout, the call stack, pointers, and how high-level abstractions are implemented. This knowledge transfers to any programming language.

Foundation for Other Languages

Many languages (Java, C#, Rust, Go) were influenced by C++. Understanding C++ makes learning other languages easier. Concepts like classes, templates (generics), and memory management appear everywhere.

Longevity

C++ code written decades ago still runs. The language prioritizes backward compatibility, ensuring your skills and code remain valuable. Unlike trendy frameworks, C++ fundamentals don't become obsolete.

Setting Up Your Environment

Before writing C++ code, you need a compiler and a text editor or IDE.

Compilers

A compiler translates your C++ source code into executable machine code. Popular compilers include:

  • GCC (GNU Compiler Collection): Free, open-source, available on Linux/Mac/Windows (via MinGW or WSL)
  • Clang: Fast, excellent error messages, default on macOS
  • MSVC (Microsoft Visual C++): Comes with Visual Studio on Windows

Windows Setup

Option 1: Install Visual Studio Community (free) with the "Desktop development with C++" workload.

Option 2: Install MinGW-w64 for GCC on Windows, then use any text editor.

Option 3: Use WSL (Windows Subsystem for Linux) to get a full Linux environment with GCC.

macOS Setup

Install Xcode Command Line Tools by running in Terminal:

xcode-select --install

This installs Clang, which you can invoke using clang++ or g++ (which is aliased to Clang on macOS).

Linux Setup

Most distributions include GCC. If not, install it:

# Debian/Ubuntu
sudo apt update
sudo apt install build-essential

# Fedora
sudo dnf install gcc-c++

# Arch
sudo pacman -S base-devel

Recommended Editors/IDEs

  • Visual Studio Code: Free, lightweight, excellent C++ extension
  • Visual Studio: Full-featured IDE for Windows
  • CLion: JetBrains IDE, cross-platform, paid (free for students)
  • Code::Blocks: Free, cross-platform, designed for C/C++

Verify Your Setup

Open a terminal and check your compiler version:

g++ --version
# or
clang++ --version

If you see version information, you're ready to write C++.

Your First Program

The traditional first program in any language prints "Hello, World!" to the screen. Create a file named hello.cpp:

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

Line-by-Line Explanation

Line 1: #include <iostream>

This is a preprocessor directive. The #include statement tells the preprocessor to include the contents of another file. <iostream> is a standard library header that provides input/output functionality (std::cout, std::cin, etc.). The angle brackets < > indicate a system/standard header.

Line 3: int main()

This is the main function. Every C++ program must have exactly one main function. Execution begins here. The int before main indicates the function returns an integer. The parentheses () contain function parameters (empty here).

Line 4: std::cout << "Hello, World!" << std::endl;

std::cout is the standard output stream (prints to the console). << is the insertion operator (sends data to the stream). "Hello, World!" is a string literal. std::endl inserts a newline and flushes the buffer. The semicolon ; ends the statement.

Line 5: return 0;

This returns the value 0 to the operating system. A return value of 0 conventionally means "success." Non-zero values indicate errors. The braces { } define the function body.

Alternative: Using '\n' Instead of std::endl

#include <iostream>

int main() {
    std::cout << "Hello, World!\n";
    return 0;
}

\n is a newline character. Unlike std::endl, it doesn't flush the buffer. Use \n for performance; use std::endl when you need to ensure output is displayed immediately.

Compilation

C++ is a compiled language. Your source code must be translated into machine code before it can run. This process involves several steps:

The Compilation Process

  1. Preprocessing: Handles directives like #include, expanding macros and including header files
  2. Compilation: Translates preprocessed code into assembly language
  3. Assembly: Converts assembly into object code (.o or .obj files)
  4. Linking: Combines object files and libraries into the final executable

Compiling with g++

# Basic compilation
g++ hello.cpp -o hello

# Run the program
./hello     # Linux/Mac
hello.exe   # Windows

Compiler Flags

Flags modify compiler behavior. Common flags include:

Flag Description
-o <name> Specify output file name
-std=c++17 Use C++17 standard
-Wall Enable all common warnings
-Wextra Enable extra warnings
-Werror Treat warnings as errors
-g Include debug information
-O2 Optimize for speed
-O3 Aggressive optimization

Recommended Compilation Command

g++ -std=c++17 -Wall -Wextra -o hello hello.cpp

This compiles using C++17, enables useful warnings, and creates an executable named hello.

Compilation Errors vs Runtime Errors

Compilation errors occur before the program runs. They're caught by the compiler (syntax errors, type mismatches, missing includes). The program won't be created until you fix them.

Runtime errors occur while the program is running. They include crashes (segmentation faults), logic errors, and exceptions. The program compiles but behaves incorrectly.

Program Structure

A typical C++ program has several components:

// Preprocessor directives
#include <iostream>
#include <string>

// Using declarations (optional)
using std::cout;
using std::endl;

// Constants and global variables (use sparingly)
const int VERSION = 1;

// Function declarations (prototypes)
void greet(const std::string& name);

// Main function
int main() {
    greet("World");
    return 0;
}

// Function definitions
void greet(const std::string& name) {
    cout << "Hello, " << name << "!" << endl;
}

Preprocessor Directives

Lines starting with # are preprocessor directives. They are processed before compilation. Common directives:

  • #include - Include a header file
  • #define - Define a macro
  • #ifdef, #ifndef, #endif - Conditional compilation
  • #pragma - Compiler-specific instructions

Header Files

Headers contain declarations that can be shared across files:

  • Standard headers: <iostream>, <vector>, <string> (no .h extension)
  • C headers: <cstdio>, <cmath>, <cstring> (C++ versions of C headers)
  • Custom headers: "myheader.h" (quotes for local files)

Statements and Expressions

A statement is a complete instruction ending with a semicolon. An expression is a combination of values, variables, and operators that produces a result.

int x = 5;           // Declaration statement
x = x + 1;           // Assignment statement
cout << x;           // Expression statement
if (x > 0) { }       // Control statement

Blocks

A block is a group of statements enclosed in braces { }. Blocks define scope - variables declared inside a block exist only within that block.

{
    int x = 10;  // x exists only in this block
}
// x is not accessible here

Namespaces

Namespaces prevent name conflicts by grouping related code. The standard library uses the std namespace.

Using the std Namespace

There are three ways to access items in a namespace:

// Method 1: Fully qualified name (preferred)
std::cout << "Hello";

// Method 2: Using declaration (imports specific items)
using std::cout;
using std::endl;
cout << "Hello" << endl;

// Method 3: Using directive (imports everything - avoid in headers)
using namespace std;
cout << "Hello" << endl;

Why Avoid "using namespace std;"

using namespace std; imports everything from the std namespace, which can cause name conflicts. It's acceptable in small programs or inside functions, but avoid it in header files or large projects.

Creating Your Own Namespace

namespace myproject {
    void doSomething() {
        std::cout << "Doing something!" << std::endl;
    }
}

// Usage
myproject::doSomething();

Comments

Comments explain your code to other developers (including your future self). They are ignored by the compiler.

Single-Line Comments

// This is a single-line comment
int x = 5;  // Comment at end of line

Multi-Line Comments

/* This is a
   multi-line comment
   that spans several lines */

/*
 * Some developers format
 * multi-line comments
 * like this for readability
 */

Documentation Comments

Many projects use documentation generators like Doxygen. They use special comment formats:

/**
 * @brief Calculates the sum of two integers.
 * @param a First integer
 * @param b Second integer
 * @return The sum of a and b
 */
int add(int a, int b) {
    return a + b;
}

Comment Best Practices

  • Explain why, not what (the code shows what)
  • Keep comments up to date when code changes
  • Don't comment obvious code
  • Use comments to explain complex algorithms or business logic
  • Comment public APIs with documentation comments

Tip

Bad: x++; // Increment x

Good: retryCount++; // Retry the operation if it failed

Coding Style

Consistent coding style makes code easier to read and maintain. While there's no single "correct" style, consistency within a project is important.

Naming Conventions

Element Convention Example
Variables camelCase or snake_case firstName or first_name
Constants ALL_CAPS MAX_SIZE
Functions camelCase or snake_case calculateSum
Classes PascalCase MyClass
Member variables m_ prefix or _ suffix m_value or value_

Indentation and Braces

// Allman style
int main()
{
    if (condition)
    {
        // code
    }
}

// K&R / One True Brace style
int main() {
    if (condition) {
        // code
    }
}

Both styles are valid. Pick one and be consistent.

General Guidelines

  • Use meaningful variable names (userAge not x)
  • Keep functions small and focused
  • Limit line length to 80-120 characters
  • Use blank lines to separate logical sections
  • Put spaces around operators: x = a + b;

Common Mistakes

Forgetting Semicolons

int x = 5   // Error: missing semicolon
int y = 10;

Every statement must end with a semicolon.

Case Sensitivity

int Main() { }  // Wrong: must be 'main', not 'Main'
Int x = 5;      // Wrong: 'int', not 'Int'

C++ is case-sensitive. main, Main, and MAIN are different.

Missing Include

int main() {
    std::cout << "Hello";  // Error: 'cout' not declared
    return 0;
}

You must include <iostream> to use cout.

Forgetting std:: Prefix

#include <iostream>
int main() {
    cout << "Hello";  // Error: 'cout' not declared
    return 0;
}

Without using namespace std; or using std::cout;, you must write std::cout.

Mismatched Braces

int main() {
    if (true) {
        // code
    // Missing closing brace for if
}

Every opening brace needs a matching closing brace.

Practice Questions

  1. Write a program that prints your name to the console.
  2. Modify the Hello World program to print on multiple lines.
  3. Create a program that prints a simple ASCII art pattern.
  4. Write a program with comments explaining each line.
  5. Compile a program with the -Wall flag and fix any warnings.
  6. Create a namespace for your project and put a function inside it.
  7. Write a program that uses both single-line and multi-line comments.
  8. Research and try the -Werror flag. What happens when you have warnings?