Book1 Getting Started With Modern CPP
Book1 Getting Started With Modern CPP
January 2025
Contents
Contents 2
1 Introduction to C++ 21
1.1 What is C++? Why use Modern C++? . . . . . . . . . . . . . . . . . . . . . . 21
1.1.1 What is C++? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.1.2 Why Use Modern C++? . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.1.3 When to Use Modern C++? . . . . . . . . . . . . . . . . . . . . . . . 26
1.1.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.2 History of C++ and the Evolution of Standards (C++11 to C++23) . . . . . . . 28
1.2.1 The Origins of C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
1.2.2 The Evolution of C++ Standards . . . . . . . . . . . . . . . . . . . . . 29
1.2.3 The Impact of Modern C++ Standards . . . . . . . . . . . . . . . . . . 35
1.2.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2
3
3.1.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
3.2 Understanding main(), #include, and using namespace std . . . . 64
3.2.1 The main() Function . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3.2.2 The #include Directive . . . . . . . . . . . . . . . . . . . . . . . . 65
3.2.3 The using namespace std; Directive . . . . . . . . . . . . . . . 66
3.2.4 Putting It All Together . . . . . . . . . . . . . . . . . . . . . . . . . . 68
3.2.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5 Control Flow 92
5.1 if, else, switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
5.1.1 Introduction to Control Flow . . . . . . . . . . . . . . . . . . . . . . . 92
5.1.2 The if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
5.1.3 Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
5.1.4 The if-else if-else Statement . . . . . . . . . . . . . . . . . . 95
5.1.5 The switch Statement . . . . . . . . . . . . . . . . . . . . . . . . . 96
5.1.6 Nested Conditional Statements . . . . . . . . . . . . . . . . . . . . . . 98
5.1.7 Best Practices for Conditional Statements . . . . . . . . . . . . . . . . 100
5.1.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
5.2 Loops (for, while, do-while) . . . . . . . . . . . . . . . . . . . . . . . . 101
5.2.1 Introduction to Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
5.2.2 The for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
5.2.3 The while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
5.2.4 The do-while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . 105
5.2.5 Loop Control Statements . . . . . . . . . . . . . . . . . . . . . . . . . 106
5.2.6 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
5.2.7 Best Practices for Loops . . . . . . . . . . . . . . . . . . . . . . . . . 108
5.2.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
6
6 Functions 110
6.1 Defining and Calling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 110
6.1.1 Introduction to Functions . . . . . . . . . . . . . . . . . . . . . . . . . 110
6.1.2 Defining a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
6.1.3 Calling a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
6.1.4 Function Parameters and Arguments . . . . . . . . . . . . . . . . . . . 112
6.1.5 Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
6.1.6 Function Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
6.1.7 Default Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
6.1.8 Function Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . 116
6.1.9 Inline Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
6.1.10 Best Practices for Functions . . . . . . . . . . . . . . . . . . . . . . . 118
6.1.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
6.2 Function Parameters and Return Values . . . . . . . . . . . . . . . . . . . . . 120
6.2.1 Introduction to Function Parameters and Return Values . . . . . . . . . 120
6.2.2 Function Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
6.2.3 Passing Arguments to Functions . . . . . . . . . . . . . . . . . . . . . 121
6.2.4 Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
6.2.5 Passing Parameters by Value vs. by Reference . . . . . . . . . . . . . . 124
6.2.6 Default Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
6.2.7 Returning Multiple Values . . . . . . . . . . . . . . . . . . . . . . . . 126
6.2.8 Best Practices for Parameters and Return Values . . . . . . . . . . . . 128
6.2.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
6.3 Inline Functions and constexpr . . . . . . . . . . . . . . . . . . . . . . . . 130
6.3.1 Introduction to Inline Functions and constexpr . . . . . . . . . . . 130
6.3.2 Inline Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
6.3.3 constexpr Functions . . . . . . . . . . . . . . . . . . . . . . . . . 131
7
Appendices 156
Appendix A: C++ Standards Overview . . . . . . . . . . . . . . . . . . . . . . . . . 156
Appendix B: Compiler Installation Guidesw . . . . . . . . . . . . . . . . . . . . . . 156
Appendix C: IDE Setup Guides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Appendix D: CMake Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Appendix E: Debugging Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Appendix F: Git Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Appendix G: Additional Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Appendix H: Sample Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
References 162
Modern C++ Handbooks
• Content:
– Introduction to C++:
9
10
– Control Flow:
– Functions:
– Practical Examples:
• Content:
– C++11 Features:
* Structured bindings.
* if and switch with initializers.
* inline variables.
* Fold expressions.
– C++20 Features:
* Ranges library.
* Coroutines.
* Three-way comparison (<=> operator).
– C++23 Features:
• Content:
• Content:
– Containers:
– Algorithms:
* Iterator categories.
* Ranges library (C++20).
– Practical Examples:
* Custom allocators.
* Performance benchmarks.
• Content:
15
* Lock-free programming.
* Custom memory management.
• Content:
– Code Quality:
– Performance Optimization:
– Design Principles:
– Security:
– Practical Examples:
– Deployment (CI/CD):
• Content:
– Scientific Computing:
* Real-time programming.
* Low-level hardware interaction.
– Practical Examples:
* Domain-specific optimizations.
• Content:
18
• Content:
– Template Metaprogramming:
* Custom allocators.
* Memory pools and arenas.
* Garbage collection techniques.
19
– Performance Tuning:
* Cache optimization.
* SIMD (Single Instruction, Multiple Data) programming.
* Profiling and benchmarking tools.
– Advanced Libraries:
• Content:
– Case Studies:
Introduction to C++
C++ is a general-purpose programming language that combines the efficiency and low-level
capabilities of C with advanced features like object-oriented programming (OOP), generic
programming, and functional programming. It was created by Bjarne Stroustrup in 1979 at
Bell Labs as an extension of the C programming language. Stroustrup's goal was to add OOP
features to C while maintaining its performance and flexibility. Over the decades, C++ has
evolved into one of the most widely used programming languages in the world, powering
everything from operating systems and game engines to scientific simulations and financial
systems.
21
22
(a) Efficiency: C++ allows developers to write highly optimized code with fine-grained
control over system resources.
(b) Flexibility: It supports multiple programming paradigms, enabling developers to
choose the best approach for their problem.
(c) Compatibility: C++ maintains backward compatibility with C and older C++
standards, allowing gradual adoption of new features.
(d) Abstraction: It provides powerful abstraction mechanisms (e.g., classes, templates)
to manage complexity in large systems.
• C++ code can be compiled and run on various platforms, including Windows,
Linux, macOS, and embedded systems.
• auto Keyword:
• Lambda Expressions:
• Smart Pointers:
– Automatically manage memory, reducing the risk of memory leaks.
• nullptr:
– Replaces NULL for null pointers, avoiding ambiguity.
3. Better Performance
Modern C++ provides tools to write more efficient code:
25
• Move Semantics:
• constexpr:
• Concurrency Support:
• Coroutines (C++20):
• Concepts (C++20):
template<typename T>
requires std::integral<T>
T add(T a, T b) { return a + b; }
5. Backward Compatibility
Modern C++ maintains backward compatibility with older C++ standards and C,
allowing developers to gradually adopt new features without rewriting existing code.
1.1.4 Summary
C++ is a powerful and versatile programming language that has evolved significantly with the
introduction of Modern C++ standards (C++11 to C++23). These standards have made C++
more expressive, safer, and easier to use while retaining its performance and flexibility. Whether
you're building a high-performance game engine, a real-time operating system, or a scientific
simulation, Modern C++ provides the tools and features you need to write efficient, reliable, and
maintainable code.
28
Released in 2011, C++11 was a transformative update that introduced many modern
features to the language. It is often referred to as ”Modern C++” and marked the
beginning of a new era for C++.
(f) nullptr:
• Replaces NULL for null pointers, avoiding ambiguity.
Released in 2014, C++14 built on the foundation of C++11, refining existing features and
adding new ones to improve usability and performance.
int x = 10;
auto lambda = [x]() { return x + 1; };
Released in 2017, C++17 introduced features that further modernized the language,
making it more expressive and easier to use.
Released in 2020, C++20 was a major update that introduced groundbreaking features,
making C++ more powerful and expressive than ever before.
(a) Concepts:
template<typename T>
requires std::integral<T>
T add(T a, T b) { return a + b; }
(c) Coroutines:
std::future<int> compute() {
co_return 42;
}
Scheduled for release in 2023, C++23 continues to build on the foundation of C++20,
introducing new features and improvements.
(a) std::expected:
(b) std::mdspan:
(c) std::print:
(d) std::stacktrace:
35
• Improved Readability: Features like auto, lambdas, and ranges make code more
concise and expressive.
1.2.4 Summary
The history of C++ is a story of continuous evolution and improvement. From its origins as ”C
with Classes” to the modern features of C++23, C++ has remained a powerful and versatile
language for a wide range of applications. The introduction of Modern C++ standards (C++11 to
C++23) has made the language more expressive, safer, and easier to use, ensuring its relevance
in the ever-changing world of software development.
Chapter 2
2. Clang: A compiler front-end for the LLVM project, known for its excellent diagnostics
and performance.
3. MSVC (Microsoft Visual C++): The compiler provided by Microsoft as part of the
Visual Studio IDE.
36
37
Most Linux distributions come with GCC pre-installed. To check if GCC is installed and
its version:
g++ --version
If GCC is not installed, you can install it using your distribution's package manager:
• Ubuntu/Debian:
• Fedora:
• Arch Linux:
• MinGW:
i. Download the MinGW installer from MinGW website.
ii. Follow the installation instructions and select the g++ package.
• WSL:
i. Enable WSL and install a Linux distribution (e.g., Ubuntu) from the
Microsoft Store.
ii. Follow the Linux instructions above to install GCC.
• Ubuntu/Debian:
• Fedora:
• Arch Linux:
clang++ --version
• LLVM:
• WSL:
(a) Enable WSL and install a Linux distribution (e.g., Ubuntu) from the Microsoft
Store.
(b) Follow the Linux instructions above to install Clang.
(b) Run the installer and select the Desktop development with C++ workload.
cl /?
41
#include <iostream>
int main() {
std::cout << "Hello, Modern C++!" << std::endl;
return 0;
}
• GCC/Clang:
• MSVC:
cl /EHsc hello.cpp
• GCC/Clang:
./hello
• MSVC:
42
hello.exe
• MSVC: Ideal for Windows development and integration with Visual Studio.
2.1.7 Summary
Installing a modern C++ compiler is the first step toward developing C++ applications. Whether
you choose GCC, Clang, or MSVC, each compiler provides robust support for Modern C++
standards and tools to help you write efficient and reliable code. By following the instructions in
this section, you can set up your development environment and start exploring the power of
Modern C++.
43
1. Visual Studio: A powerful IDE from Microsoft, ideal for Windows development.
2. CLion: A cross-platform IDE from JetBrains, known for its intelligent code analysis.
3. VS Code: A lightweight, extensible code editor from Microsoft, with support for C++ via
extensions.
• Launch the installer and select the Desktop development with C++ workload.
• Ensure that the MSVC compiler and Windows SDK are selected.
(c) Complete the Installation:
• Follow the on-screen instructions to complete the installation.
• Launch Visual Studio after installation.
1. Installing CLion
3. Configuring CLion
• Set Up Compiler:
– Use the built-in code analysis tools to detect issues and improve code quality.
1. Installing VS Code
• Click on the Extensions icon in the Activity Bar or press Ctrl + Shift +
X.
cmake_minimum_required(VERSION 3.10)
project(MyProject)
set(CMAKE_CXX_STANDARD 20)
add_executable(MyProject main.cpp)
• Visual Studio: Best for Windows development with deep integration with MSVC.
• VS Code: Lightweight and extensible, suitable for developers who prefer a customizable
environment.
2.2.6 Summary
Setting up an IDE is a crucial step in creating a productive C++ development environment.
Whether you choose Visual Studio, CLion, or VS Code, each IDE provides powerful tools and
features to help you write, debug, and optimize Modern C++ code. By following the instructions
49
in this section, you can configure your preferred IDE and start building C++ applications with
confidence.
50
• Integration: CMake integrates with IDEs (e.g., Visual Studio, CLion) and build
tools (e.g., Make, Ninja).
• Modularity: CMake allows you to organize your project into reusable modules and
libraries.
• Ubuntu/Debian:
51
• Fedora:
• Arch Linux:
1. Project Structure
A typical CMake project has the following structure:
MyProject/
CMakeLists.txt
include/
MyLibrary.h
src/
MyLibrary.cpp
main.cpp
# Add an executable
add_executable(MyProject src/main.cpp src/MyLibrary.cpp)
# Include directories
target_include_directories(MyProject PUBLIC include)
53
• include/MyLibrary.h:
#ifndef MYLIBRARY_H
#define MYLIBRARY_H
void printMessage();
#endif // MYLIBRARY_H
• src/MyLibrary.cpp:
#include "MyLibrary.h"
#include <iostream>
void printMessage() {
std::cout << "Hello from MyLibrary!" << std::endl;
}
• src/main.cpp:
#include "MyLibrary.h"
int main() {
printMessage();
return 0;
}
mkdir build
cd build
cmake ..
• Linux/macOS:
make
• Linux/macOS:
./MyProject
• Windows:
Run the generated .exe file from the command line or Visual Studio.
55
# Add a library
add_library(MyLibrary src/MyLibrary.cpp)
# Enable warnings
target_compile_options(MyProject PRIVATE -Wall -Wextra -pedantic)
cmake --install .
2. CLion
• CLion will detect the CMakeLists.txt file and configure the project.
3. VS Code
• Use the CMake Tools extension to configure and build the project.
57
2.3.7 Summary
CMake is a powerful and flexible tool for managing C++ projects. It simplifies the build process,
supports cross-platform development, and integrates with popular IDEs. By following the
instructions in this section, you can set up and manage your C++ projects using CMake,
ensuring a consistent and efficient development workflow.
Chapter 3
1. The Code
58
59
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
• This is the main function, which is the entry point of every C++ program. The
program execution begins here.
• The int return type indicates that the function returns an integer value. By
convention, returning 0 indicates that the program executed successfully.
• std::cout is the standard output stream object, used to print text to the
console.
• The << operator is the insertion operator, which sends the text ”Hello,
World!” to the output stream.
• std::endl is a manipulator that inserts a newline character and flushes the
output buffer.
• This statement ends the main function and returns the value 0 to the operating
system, indicating that the program completed successfully.
To compile the program, you need a C++ compiler such as GCC, Clang, or MSVC.
– MSVC:
cl /EHsc hello.cpp
• Linux/macOS:
./hello
• Windows:
hello.exe
Hello, World!
• The program uses the std::cout and std::endl objects from the C++
Standard Library, which are part of Modern C++.
2. Namespaces:
• The std:: prefix indicates that cout and endl are part of the std namespace,
which is a Modern C++ feature for organizing code and avoiding name conflicts.
3. Return Type:
• The int return type of the main function is a standard practice in Modern C++.
62
We can use the auto keyword to automatically deduce the type of a variable:
#include <iostream>
int main() {
auto message = "Hello, World!";
std::cout << message << std::endl;
return 0;
}
#include <iostream>
#include <vector>
int main() {
std::vector<std::string> messages = {"Hello,", "World!"};
for (const auto& word : messages) {
std::cout << word << " ";
}
std::cout << std::endl;
return 0;
}
63
#include <iostream>
int main() {
auto printMessage = []() {
std::cout << "Hello, World!" << std::endl;
};
printMessage();
return 0;
}
3.1.6 Summary
The ”Hello, World!” program is a simple yet powerful introduction to Modern C++. It
demonstrates the basic structure of a C++ program, including the use of the Standard Library,
namespaces, and the main function. By enhancing the program with Modern C++ features like
auto, range-based for loops, and lambda expressions, we can explore the expressive power
and flexibility of the language.
This section provides a comprehensive guide to writing, compiling, and running the ”Hello,
World!” program in Modern C++. It also introduces key Modern C++ features and best
practices, setting the stage for more advanced topics in the book.
64
int main() {
// Program code goes here
return 0;
}
2. Command-Line Arguments
The main() function can also accept command-line arguments, which allow you to pass
parameters to the program when it is executed:
1. Syntax of #include
The #include directive has the following syntax:
#include <header_file>
or
66
#include "header_file"
#include <iostream>
#include "my_header.h"
1. Namespaces in C++
• Example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
– Here, cout and endl can be used directly without the std:: prefix.
• Pros:
• Cons:
4. Best Practices
• Avoid in Header Files: Do not use using namespace std; in header files to
prevent name conflicts in other files that include the header.
• Use in Source Files: It is generally safe to use using namespace std; in
source files, but consider using the std:: prefix for clarity and to avoid potential
conflicts.
int main() {
// Print "Hello, World!" to the console
cout << "Hello, World!" << endl;
1. Explanation
• Brings all names from the std namespace into the current scope, allowing us to
use cout and endl without the std:: prefix.
• Defines the main() function, which is the entry point of the program.
• Uses cout to print ”Hello, World!” to the console and endl to insert a
newline.
3.2.5 Summary
Understanding the main() function, the #include directive, and the using namespace
std; directive is essential for writing and understanding C++ programs. These concepts form
the foundation of C++ programming and are used in virtually every C++ program. By mastering
these basics, you will be well-prepared to explore more advanced topics in Modern C++.
Chapter 4
In C++, a variable is a named storage location in memory that holds a value of a specific data
type. Data types define the kind of data a variable can store, such as integers, floating-point
numbers, or boolean values. Understanding variables and data types is fundamental to writing
C++ programs.
To use a variable in C++, you must first declare it by specifying its data type and name. You can
also initialize the variable by assigning it a value at the time of declaration.
70
71
data_type variable_name;
3. Example
1. int (Integer)
• Example:
• Example:
3. bool (Boolean)
• Example:
2. Example
73
3. Benefits of auto
4. Limitations of auto
• signed: Allows both positive and negative values (default for int).
• unsigned: Allows only non-negative values.
• Example:
• short: Reduces the size of the data type (e.g., short int).
• long: Increases the size of the data type (e.g., long int).
• Example:
int i = 10;
double d = i; // Implicit conversion from int to double
double d = 3.14;
int i = static_cast<int>(d); // Explicit conversion from double
,→ to int
75
4.1.7 Constants
Constants are variables whose values cannot be changed after initialization. They are declared
using the const keyword.
2. Example
#include <iostream>
int main() {
// Declare and initialize variables
int age = 25;
double height = 5.9;
bool isStudent = true;
return 0;
}
1. Explanation
(a) Variables:
(b) Output:
4.1.9 Summary
Variables and data types are fundamental concepts in C++ programming. By understanding how
to declare and initialize variables, use fundamental data types like int, double, and bool,
and leverage the auto keyword for type inference, you can write more efficient and readable
code. These concepts form the foundation for more advanced topics in Modern C++.
77
• The << operator is called the insertion operator and is used to send data to the
output stream.
2. Example
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
78
• Output:
Hello, World!
3. Chaining Output
You can chain multiple << operators to output multiple items in a single statement:
4. std::endl
• The std::endl manipulator inserts a newline character and flushes the output
buffer.
• Example:
– Output:
Line 1
Line 2
• The >> operator is called the extraction operator and is used to read data from the
input stream.
2. Example
#include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "You are " << age << " years old." << std::endl;
return 0;
}
3. Chaining Input
You can chain multiple >> operators to input multiple values in a single statement:
80
int x, y;
std::cout << "Enter two numbers: ";
std::cin >> x >> y;
std::cout << "You entered: " << x << " and " << y << std::endl;
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (std::cin.fail()) {
std::cerr << "Invalid input! Please enter a number." <<
,→ std::endl;
} else {
std::cout << "You entered: " << number << std::endl;
}
return 0;
}
81
#include <iostream>
#include <limits>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
if (std::cin.fail()) {
std::cin.clear(); // Clear the error state
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
,→ '\n'); // Ignore invalid input
std::cerr << "Invalid input! Please enter a number." <<
,→ std::endl;
} else {
std::cout << "You entered: " << number << std::endl;
}
return 0;
}
C++ provides several manipulators to format output, such as setting the precision of
floating-point numbers or aligning text.
#include <iostream>
#include <iomanip> // For std::setprecision
int main() {
double pi = 3.141592653589793;
std::cout << "Pi to 3 decimal places: " <<
,→ std::setprecision(3) << pi << std::endl;
return 0;
}
• Output:
#include <iostream>
#include <iomanip> // For std::setw
int main() {
std::cout << std::setw(10) << "Hello" << std::setw(10) <<
,→ "World" << std::endl;
return 0;
}
• Output:
83
Hello World
#include <iostream>
#include <iomanip>
int main() {
// Declare variables
std::string name;
int age;
double height;
// Input
std::cout << "Enter your name: ";
std::getline(std::cin, name); // Read a full line of text
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Enter your height (in meters): ";
std::cin >> height;
// Output
std::cout << std::fixed << std::setprecision(2); // Set precision
,→ for floating-point numbers
std::cout << "\nName: " << name << std::endl;
std::cout << "Age: " << age << " years" << std::endl;
std::cout << "Height: " << height << " meters" << std::endl;
84
return 0;
}
(a) Explanation
i. Input:
• The program prompts the user to enter their name, age, and height.
• std::getline is used to read the full name, including spaces.
ii. Output:
• The program prints the user's name, age, and height with formatted
precision.
4.2.7 Summary
Input and output operations are fundamental to C++ programming. By mastering the use
of std::cin and std::cout, you can create interactive programs that communicate
effectively with users. Additionally, understanding how to handle input errors and format
output ensures that your programs are robust and user-friendly.
85
Operators are symbols that perform operations on variables and values. In C++, operators
are categorized based on their functionality. The three main types of operators we will
cover in this section are:
Arithmetic operators are used to perform basic mathematical operations such as addition,
subtraction, multiplication, and division.
(b) Examples
#include <iostream>
int main() {
int a = 10, b = 3;
int d = 8;
std::cout << "d-- = " << d-- << std::endl; // 8
,→ (post-decrement)
std::cout << "--d = " << --d << std::endl; // 6
,→ (pre-decrement)
return 0;
}
• Integer Division: When both operands are integers, the / operator performs
integer division, discarding the fractional part.
• Modulus Operator (%): Works only with integer operands and returns the
remainder of the division.
• Increment (++) and Decrement (--):
– Post-increment (a++): Returns the original value of a and then increments
it.
– Pre-increment (++a): Increments a and then returns the new value.
Relational operators are used to compare two values or expressions. They return a boolean
value (true or false).
(b) Examples
88
#include <iostream>
int main() {
int a = 10, b = 20;
return 0;
}
• Relational operators are often used in conditional statements (e.g., if, while)
to control the flow of a program.
• The result of a relational operation is a boolean value (true or false), which
is represented as 1 or 0 in C++.
Logical operators are used to combine or negate boolean expressions. They are often used
in decision-making and looping constructs.
(b) Examples
#include <iostream>
int main() {
bool a = true, b = false;
return 0;
}
• Logical AND (&&): Returns true only if both operands are true.
• Logical OR (||): Returns true if at least one operand is true.
• Logical NOT (!): Negates the boolean value of the operand.
• Logical operators are often used in combination with relational operators to
form complex conditions.
90
#include <iostream>
int main() {
int a = 10, b = 20, c = 30;
return 0;
}
When multiple operators are used in an expression, their evaluation order is determined by
operator precedence and associativity.
i. Example
4.3.7 Summary
Control Flow
Control flow statements allow you to control the execution of your program based on
certain conditions. In C++, the primary conditional statements are:
(a) if and else: Used to execute code blocks based on boolean conditions.
(b) switch: Used to select one of many code blocks to execute based on the value of a
variable.
92
93
(a) Syntax
if (condition) {
// Code to execute if condition is true
}
(b) Example
#include <iostream>
int main() {
int age = 20;
return 0;
}
• Output:
5.1.3 Statement
The if-else statement allows you to execute one block of code if a condition is true
and another block if the condition is false.
(a) Syntax
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
(b) Example
#include <iostream>
int main() {
int age = 15;
return 0;
}
• Output:
95
• The else block is optional and is executed only if the if condition is false.
The if-else if-else statement allows you to test multiple conditions and execute
different code blocks based on which condition is true.
(a) Syntax
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if all conditions are false
}
(b) Example
#include <iostream>
int main() {
int score = 85;
return 0;
}
• Output:
Grade: B
The switch statement allows you to select one of many code blocks to execute based on
the value of a variable or expression.
(a) Syntax
switch (expression) {
case value1:
// Code to execute if expression == value1
97
break;
case value2:
// Code to execute if expression == value2
break;
// More cases...
default:
// Code to execute if expression does not match any case
}
(b) Example
#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
case 4:
std::cout << "Thursday" << std::endl;
break;
case 5:
std::cout << "Friday" << std::endl;
break;
98
case 6:
std::cout << "Saturday" << std::endl;
break;
case 7:
std::cout << "Sunday" << std::endl;
break;
default:
std::cout << "Invalid day" << std::endl;
}
return 0;
}
• Output:
Wednesday
Conditional statements can be nested within each other to handle more complex logic.
99
(a) Example
#include <iostream>
int main() {
int age = 20;
bool isStudent = true;
return 0;
}
• Output:
(a) Use Braces {}: Always use braces for if, else, and switch blocks, even if they
contain only one statement. This improves readability and avoids bugs.
(b) Avoid Deep Nesting: Deeply nested if statements can make code hard to read.
Consider refactoring or using functions to simplify logic.
(c) Use switch for Multiple Conditions: When comparing a single variable against
multiple values, prefer switch over multiple if-else if statements for better
readability.
(d) Default Case in switch: Always include a default case in switch statements
to handle unexpected values.
5.1.8 Summary
Conditional statements (if, else, and switch) are essential tools for controlling the
flow of your C++ programs. They allow you to execute different blocks of code based on
specific conditions, making your programs more dynamic and flexible. By mastering these
constructs and following best practices, you can write clean, efficient, and maintainable
code.
101
Loops are control flow statements that allow you to execute a block of code repeatedly
based on a condition. They are essential for tasks that require repetitive operations, such
as iterating over arrays, processing data, or implementing algorithms. In C++, there are
three primary types of loops:
(a) for Loop: Used when the number of iterations is known or can be determined.
(b) while Loop: Used when the number of iterations is not known in advance, and the
loop continues as long as a condition is true.
(c) do-while Loop: Similar to the while loop, but the condition is evaluated after
the loop body, ensuring that the loop executes at least once.
The for loop is used when you know how many times you want to execute a block of
code. It consists of three parts: initialization, condition, and update.
(a) Syntax
(b) Example
102
#include <iostream>
int main() {
for (int i = 0; i < 5; ++i) {
std::cout << "Iteration: " << i << std::endl;
}
return 0;
}
• Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Syntax
Example
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
return 0;
}
• Output:
1 2 3 4 5
The while loop is used when the number of iterations is not known in advance, and the
loop continues as long as a condition is true.
104
(a) Syntax
while (condition) {
// Code to execute
}
(b) Example
#include <iostream>
int main() {
int count = 0;
return 0;
}
• Output:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
The do-while loop is similar to the while loop, but the condition is evaluated after the
loop body. This ensures that the loop executes at least once.
(a) Syntax
do {
// Code to execute
} while (condition);
(b) Example
#include <iostream>
int main() {
int count = 0;
do {
std::cout << "Count: " << count << std::endl;
++count;
} while (count < 5);
return 0;
}
• Output:
Count: 0
Count: 1
Count: 2
106
Count: 3
Count: 4
#include <iostream>
int main() {
for (int i = 0; i < 10; ++i) {
if (i == 5) {
break; // Exit the loop when i == 5
}
std::cout << i << " ";
}
return 0;
}
107
• Output:
0 1 2 3 4
#include <iostream>
int main() {
for (int i = 0; i < 10; ++i) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
std::cout << i << " ";
}
return 0;
}
• Output:
1 3 5 7 9
Loops can be nested within each other to handle more complex tasks, such as working
with multi-dimensional arrays.
(a) Example
108
#include <iostream>
int main() {
for (int i = 1; i <= 3; ++i) {
for (int j = 1; j <= 3; ++j) {
std::cout << "(" << i << ", " << j << ") ";
}
std::cout << std::endl;
}
return 0;
}
• Output:
(a) Use the Right Loop: Choose the loop type (for, while, do-while) based on
the problem requirements.
(b) Avoid Infinite Loops: Ensure that the loop condition will eventually become
false.
109
(c) Minimize Loop Nesting: Deeply nested loops can be hard to read and debug.
Consider refactoring or using functions to simplify logic.
(d) Use Range-Based for Loops: Prefer range-based for loops when iterating over
collections.
(e) Limit Scope of Loop Variables: Declare loop variables (e.g., i) within the loop to
limit their scope.
5.2.8 Summary
Loops (for, while, do-while) are powerful tools for controlling repetitive tasks in
C++ programs. By mastering these constructs and following best practices, you can write
efficient, readable, and maintainable code. Whether you're iterating over collections,
processing data, or implementing algorithms, loops are an essential part of your
programming toolkit.
Chapter 6
Functions
A function is a reusable block of code that performs a specific task. Functions are
essential for organizing code, improving readability, and promoting code reuse. In C++,
functions can take input parameters, perform operations, and return results.
To define a function in C++, you need to specify its return type, name, parameters, and
body.
(a) Syntax
110
111
return_type function_name(parameter_list) {
// Function body
// Code to execute
return value; // Optional, depending on return_type
}
• return type: The type of value the function returns (e.g., int, double,
void).
• function name: The name of the function, which should be descriptive and
follow naming conventions.
• parameter list: A comma-separated list of parameters (inputs) the
function accepts. Each parameter has a type and a name.
• function body: The block of code that defines what the function does.
• return statement: Used to return a value to the caller. If the return type is
void, the return statement is optional.
(b) Example
#include <iostream>
// Function definition
int add(int a, int b) {
return a + b;
}
Once a function is defined, you can call it from other parts of your program by using its
name and providing the required arguments.
112
(a) Syntax
function_name(arguments);
(b) Example
#include <iostream>
// Function definition
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(3, 5); // Function call
std::cout << "Result: " << result << std::endl; // Output: 8
return 0;
}
(a) Example
113
#include <iostream>
int main() {
printMessage("Hello, World!"); // Function call with argument
return 0;
}
• Output:
Hello, World!
Functions can return a value to the caller using the return statement. The return type
must match the function's declared return type.
(a) Example
#include <iostream>
int main() {
double result = multiply(2.5, 4.0); // Function call
std::cout << "Result: " << result << std::endl; // Output:
,→ 10.0
return 0;
}
#include <iostream>
// void function
void greet() {
std::cout << "Hello, User!" << std::endl;
}
int main() {
greet(); // Function call
return 0;
}
• Output:
Hello, User!
115
A function prototype declares a function's name, return type, and parameters without
defining its body. It allows you to call a function before defining it.
(a) Syntax
return_type function_name(parameter_list);
(b) Example
#include <iostream>
// Function prototype
int add(int a, int b);
int main() {
int result = add(3, 5); // Function call
std::cout << "Result: " << result << std::endl; // Output: 8
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
C++ allows you to specify default arguments for function parameters. If an argument is
not provided when the function is called, the default value is used.
116
(a) Syntax
(b) Example
#include <iostream>
int main() {
printMessage(); // Uses default argument
printMessage("Goodbye, World!"); // Overrides default
,→ argument
return 0;
}
• Output:
Hello, World!
Goodbye, World!
C++ supports function overloading, which allows you to define multiple functions with
the same name but different parameter lists.
117
(a) Example
#include <iostream>
// Overloaded functions
int add(int a, int b) {
return a + b;
}
int main() {
std::cout << "Integer addition: " << add(3, 5) << std::endl;
,→ // Output: 8
std::cout << "Double addition: " << add(2.5, 4.0) <<
,→ std::endl; // Output: 6.5
return 0;
}
The inline keyword suggests that the compiler replace the function call with the
function's body to reduce overhead. This is useful for small, frequently called functions.
(a) Syntax
(b) Example
#include <iostream>
// Inline function
inline int square(int x) {
return x * x;
}
int main() {
std::cout << "Square of 5: " << square(5) << std::endl; //
,→ Output: 25
return 0;
}
(a) Use Descriptive Names: Choose meaningful names for functions and parameters.
(b) Keep Functions Small: Functions should perform a single, well-defined task.
(c) Avoid Global Variables: Prefer passing data to functions via parameters.
(d) Use Default Arguments Sparingly: Default arguments can make code harder to
understand if overused.
(e) Document Functions: Use comments to describe the purpose, parameters, and
return value of functions.
6.1.11 Summary
Functions are a cornerstone of C++ programming, enabling code reuse, modularity, and
readability. By mastering the concepts of defining and calling functions, using parameters
119
and return values, and leveraging advanced features like function overloading and default
arguments, you can write clean, efficient, and maintainable code.
120
Function parameters and return values are fundamental to how functions interact with the
rest of your program. Parameters allow you to pass data into a function, while return
values allow a function to send data back to the caller. Understanding how to use
parameters and return values effectively is key to writing modular and reusable code.
Function parameters are variables declared in the function signature that act as
placeholders for the values (arguments) passed to the function when it is called.
(a) Syntax
(b) Example
#include <iostream>
int main() {
printMessage("Hello, World!"); // Function call with argument
return 0;
}
• Output:
Hello, World!
#include <iostream>
int main() {
int result = add(3, 5); // Function call
std::cout << "Result: " << result << std::endl; // Output: 8
return 0;
}
When calling a function, you pass arguments that correspond to the function's parameters.
The arguments can be literals, variables, or expressions.
122
(a) Example
#include <iostream>
int main() {
int x = 10, y = 20;
printSum(x, y); // Pass variables as arguments
printSum(5, 15); // Pass literals as arguments
return 0;
}
• Output:
Sum: 30
Sum: 20
Functions can return a value to the caller using the return statement. The return type
must match the function's declared return type.
(a) Syntax
return_type function_name(parameters) {
// Function body
123
(b) Example
#include <iostream>
int main() {
double result = multiply(2.5, 4.0); // Function call
std::cout << "Result: " << result << std::endl; // Output:
,→ 10.0
return 0;
}
#include <iostream>
// void function
void greet() {
std::cout << "Hello, User!" << std::endl;
}
124
int main() {
greet(); // Function call
return 0;
}
• Output:
Hello, User!
C++ allows you to pass parameters by value or by reference, which affects how the
function interacts with the arguments.
Example
#include <iostream>
// Pass by value
void increment(int x) {
++x; // Changes the local copy of x
}
int main() {
int a = 5;
125
increment(a);
std::cout << "a: " << a << std::endl; // Output: 5
,→ (unchanged)
return 0;
}
Example
#include <iostream>
// Pass by reference
void increment(int& x) {
++x; // Changes the original argument
}
int main() {
int a = 5;
increment(a);
std::cout << "a: " << a << std::endl; // Output: 6 (changed)
return 0;
}
C++ allows you to specify default arguments for function parameters. If an argument is
not provided when the function is called, the default value is used.
126
(a) Syntax
(b) Example
#include <iostream>
int main() {
printMessage(); // Uses default argument
printMessage("Goodbye, World!"); // Overrides default
,→ argument
return 0;
}
• Output:
Hello, World!
Goodbye, World!
C++ functions can return only one value directly. However, you can return multiple values
using:
127
#include <iostream>
int main() {
Result result = compute(3, 4);
std::cout << "Sum: " << result.sum << ", Product: " <<
,→ result.product << std::endl;
return 0;
}
• Output:
Sum: 7, Product: 12
#include <iostream>
int main() {
int sum, product;
compute(3, 4, sum, product);
std::cout << "Sum: " << sum << ", Product: " << product <<
,→ std::endl;
return 0;
}
• Output:
Sum: 7, Product: 12
(a) Use Descriptive Names: Choose meaningful names for parameters and return
values.
(b) Prefer Pass by Reference for Large Objects: Avoid copying large objects by
passing them by reference.
(c) Use const for Read-Only Parameters: Mark parameters as const if they are
not modified inside the function.
129
(d) Avoid Overusing Default Arguments: Default arguments can make code harder to
understand if overused.
(e) Document Parameters and Return Values: Use comments to describe the purpose
and behavior of parameters and return values.
6.2.9 Summary
Function parameters and return values are essential for creating flexible and reusable
functions in C++. By understanding how to pass arguments, return values, and use
advanced features like default arguments and pass-by-reference, you can write efficient
and maintainable code. These concepts form the foundation for more advanced topics like
function overloading, templates, and lambda expressions.
130
C++ provides two powerful features to optimize and enhance the functionality of
functions: inline functions and constexpr functions. These features allow you to
improve performance, reduce overhead, and enable compile-time computations.
The inline keyword is a suggestion to the compiler to replace the function call with the
actual code of the function. This can reduce the overhead of function calls, especially for
small, frequently called functions.
(a) Syntax
(b) Example
#include <iostream>
// Inline function
inline int square(int x) {
return x * x;
}
131
int main() {
int result = square(5); // Function call
std::cout << "Square of 5: " << result << std::endl; //
,→ Output: 25
return 0;
}
The constexpr keyword indicates that a function can be evaluated at compile time if its
arguments are constant expressions. This allows for compile-time computations, which
can improve performance and enable certain optimizations.
(a) Syntax
132
(b) Example
#include <iostream>
// constexpr function
constexpr int factorial(int n) {
return (n <= 1) ? 1 : n * factorial(n - 1);
}
int main() {
constexpr int result = factorial(5); // Compile-time
,→ computation
std::cout << "Factorial of 5: " << result << std::endl; //
,→ Output: 120
return 0;
}
You can combine inline and constexpr to create functions that are both inlined and
evaluated at compile time when possible.
(a) Example
#include <iostream>
int main() {
constexpr int result = square(5); // Compile-time computation
std::cout << "Square of 5: " << result << std::endl; //
,→ Output: 25
return 0;
}
#include <iostream>
#include <cmath>
int main() {
double mag = magnitude(3.0, 4.0, 5.0); // Function call
std::cout << "Magnitude: " << mag << std::endl; // Output:
,→ 7.07107
return 0;
}
#include <iostream>
int main() {
constexpr int result = factorial(5); // Compile-time
,→ computation
std::cout << "Factorial of 5: " << result << std::endl; //
,→ Output: 120
return 0;
}
(a) Use inline for Small Functions: Apply inline to small, frequently called
functions to reduce call overhead.
(c) Combine inline and constexpr: When appropriate, combine both keywords
to leverage their benefits.
(d) Avoid Overuse: Do not overuse inline or constexpr for large or complex
functions, as it can lead to code bloat or compilation errors.
136
6.3.7 Summary
Inline functions and constexpr functions are powerful tools in C++ for optimizing
performance and enabling compile-time computations. By understanding their syntax, use
cases, and best practices, you can write efficient and maintainable code that takes full
advantage of Modern C++ features.
Chapter 7
Practical Examples
7.1.1 Introduction
In this section, we will create two simple programs to reinforce the concepts of variables,
control flow, functions, and input/output in C++. These programs are:
(b) Number Guessing Game: A game where the user guesses a randomly generated
number.
These programs will help you practice and solidify your understanding of Modern C++.
137
138
The calculator program will take two numbers and an operation (+, -, *, /) as input from
the user and display the result.
#include <iostream>
int main() {
double num1, num2;
char operation;
// Input
std::cout << "Enter first number: ";
std::cin >> num1;
break;
case '-':
std::cout << "Result: " << (num1 - num2) <<
,→ std::endl;
break;
case '*':
std::cout << "Result: " << (num1 * num2) <<
,→ std::endl;
break;
case '/':
if (num2 != 0) {
std::cout << "Result: " << (num1 / num2) <<
,→ std::endl;
} else {
std::cout << "Error: Division by zero!" <<
,→ std::endl;
}
break;
default:
std::cout << "Invalid operation!" << std::endl;
}
return 0;
}
The number guessing game will generate a random number between 1 and 100, and the
user will guess the number. The program will provide feedback (too high, too low) until
the user guesses correctly.
#include <iostream>
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
int main() {
// Seed the random number generator
std::srand(static_cast<unsigned int>(std::time(0)));
do {
// Input
std::cout << "Enter your guess: ";
std::cin >> guess;
++attempts;
return 0;
}
(a) Modularize Code: Break the program into functions for better readability and
reusability.
(b) Error Handling: Validate user input to handle invalid entries gracefully.
(c) Comments: Use comments to explain the purpose of each section of code.
(d) Testing: Test the program with different inputs to ensure it works as expected.
7.1.5 Summary
The calculator and number guessing game programs are excellent examples to reinforce
fundamental C++ concepts. By writing and understanding these programs, you will gain
confidence in using variables, control flow, functions, and input/output operations. These
skills form the foundation for more advanced programming tasks in Modern C++.
Chapter 8
Debugging is the process of identifying and resolving errors (bugs) in your code. Effective
debugging is crucial for developing reliable and efficient software. In C++, you can use
tools like GDB (a command-line debugger) or IDE Debuggers (e.g., Visual Studio,
CLion, VS Code) to debug your programs.
GDB (GNU Debugger) is a powerful command-line tool for debugging C++ programs. It
allows you to inspect the state of your program, set breakpoints, step through code, and
analyze crashes.
143
144
1.2.1 Compiling for Debugging To use GDB, you must compile your program with
debugging information. Use the -g flag with your compiler:
bash
Copy
gdb ./my_program
1.2.3 Basic GDB Commands Here are some essential GDB commands:
Command Description
break <line> Set a breakpoint at a specific line number.
run Start the program.
next Execute the next line of code (step over).
step Execute the next line of code (step into).
print <variable> Print the value of a variable.
backtrace Display the call stack.
continue Continue execution until the next breakpoint.
quit Exit GDB.
#include <iostream>
int main() {
int x = 10;
int y = 0;
int z = x / y; // Division by zero
std::cout << "z: " << z << std::endl;
return 0;
}
gdb ./my_program
break 6
run
print x
print y
next
quit
Modern IDEs like Visual Studio, CLion, and VS Code provide integrated debugging
tools with a graphical interface. These tools simplify debugging by allowing you to set
breakpoints, inspect variables, and step through code visually.
• Click in the left margin next to the line of code where you want to set a
breakpoint.
• Hover over variables to see their values, or use the Watch window.
• Use F10 (Step Over) or F11 (Step Into) to execute code line by line.
• Use the Call Stack window to inspect the sequence of function calls.
• Click in the left margin next to the line of code where you want to set a
breakpoint.
• Click in the left margin next to the line of code where you want to set a
breakpoint.
• Use F10 (Step Over) or F11 (Step Into) to execute code line by line.
• Use the Call Stack pane to inspect the sequence of function calls.
• Use Step Over to execute the next line of code without entering functions.
• Use Step Into to enter and debug functions.
• The call stack shows the sequence of function calls leading to the current point
of execution.
• Use the call stack to trace the origin of errors.
• Use debugging tools to identify the cause of crashes (e.g., segmentation faults).
• Inspect the call stack and variable values at the point of failure.
• Add logging statements to track the flow of execution and variable values.
• Verify that your assumptions about the program's behavior are correct.
8.1.6 Summary
Debugging is an essential skill for any programmer. By mastering tools like GDB and
IDE Debuggers, you can efficiently identify and resolve errors in your C++ programs.
Whether you prefer command-line tools or graphical interfaces, understanding debugging
techniques will help you develop more reliable and efficient software.
Version control is a system that records changes to files over time, allowing you to track
modifications, revert to previous states, and collaborate with others. Git is the most widely
used version control system, known for its speed, flexibility, and distributed nature.
(a) Track Changes: Keep a history of all changes made to your code.
(b) Collaborate: Work with others on the same project without conflicts.
(c) Revert Mistakes: Easily revert to a previous version if something goes wrong.
(d) Branching and Merging: Create separate branches for new features or experiments
and merge them back into the main codebase.
(e) Backup: Maintain a backup of your code in a remote repository.
(a) On Linux
(b) On macOS
(c) On Windows
Download and install Git from the official website.
(c) Branch: A separate line of development. The default branch is usually called main
or master.
(f) Pull: Download changes from a remote repository to your local machine.
Command Description
git init Initialize a new Git repository.
git clone <url> Clone a remote repository to your local machine.
git status Show the status of the working directory.
git add <file> Stage changes for the next commit.
git commit -m "msg" Commit staged changes with a message.
git push Push local commits to a remote repository.
git pull Pull changes from a remote repository.
git branch List all branches in the repository.
git checkout Switch to a different branch.
<branch>
git merge <branch> Merge changes from another branch.
mkdir my_project
cd my_project
git init
Branching allows you to work on new features or experiments without affecting the main
codebase.
Remote repositories allow you to collaborate with others and back up your code.
155
(a) Commit Often: Make small, frequent commits with clear messages.
(b) Write Good Commit Messages: Use descriptive messages that explain the changes.
(c) Use Branches: Create branches for new features or bug fixes.
(d) Review Changes: Use git diff to review changes before committing.
(e) Sync Regularly: Pull changes from the remote repository frequently to avoid
conflicts.
8.2.11 Summary
Git is an essential tool for version control, enabling you to track changes, collaborate with
others, and manage your code effectively. By mastering basic Git commands and
workflows, you can improve your productivity and ensure the integrity of your projects.
Appendices
• C++11: Introduction of auto, range-based for loops, smart pointers, and lambda
expressions.
• C++14: Generalized lambda captures, return type deduction, and binary literals.
(b) Clang
156
157
(b) CLion
(c) VS Code
• What is CMake?
A cross-platform build system for managing C++ projects.
cmake_minimum_required(VERSION 3.10)
project(MyProject)
add_executable(MyProgram main.cpp)
• Building a Project:
mkdir build
cd build
cmake ..
make
• Basic commands:
– gdb ./my program
– break main
– run
– print variable name
• Visual Studio: Use the built-in debugger with breakpoints and watch windows.
• CLion: Integrated GDB/LLDB support.
• VS Code: Use the C++ debugger extension.
159
• Initializing a Repository:
git init
git add .
git commit -m "Initial commit"
• Cloning a Repository:
• Basic Commands:
– git status
– git pull
– git push
– git branch
(a) Books:
(b) Websites:
• cppreference.com
• isocpp.org
160
• LearnCpp.com
• GeeksforGeeks C++ Programming
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
#include <iostream>
int main() {
double a, b;
char op;
std::cout << "Enter two numbers and an operator (+, -, *, /):
,→ ";
std::cin >> a >> b >> op;
switch (op) {
case '+': std::cout << "Result: " << a + b << std::endl;
,→ break;
case '-': std::cout << "Result: " << a - b << std::endl;
,→ break;
case '*': std::cout << "Result: " << a * b << std::endl;
,→ break;
161
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
std::srand(std::time(0));
int number = std::rand() % 100 + 1;
int guess;
std::cout << "Guess a number between 1 and 100: ";
while (std::cin >> guess) {
if (guess < number) std::cout << "Too low! Try again: ";
else if (guess > number) std::cout << "Too high! Try
,→ again: ";
else {
std::cout << "Correct! You win!" << std::endl;
break;
}
}
return 0;
}
References
Books:
• The definitive guide to C++ by its creator. A must-read for understanding the
language in depth.
• Focuses on best practices and modern C++ features (C++11, C++14, and
beyond).
(c) ”C++ Primer” by Stanley B. Lippman, Josée Lajoie, and Barbara E. Moo
162
163
(a) cppreference.com
• A comprehensive and reliable online reference for the C++ standard library and
language features.
(b) isocpp.org
• The official website for the C++ programming language, maintained by the ISO
C++ Foundation.
(c) Stack Overflow (C++ Tag)
• A community-driven Q&A platform for solving specific C++ problems and
learning from others.
(d) LearnCpp.com
• A beginner-friendly tutorial website for learning C++.
(e) GeeksforGeeks C++ Programming Language
• A resource for tutorials, articles, and coding challenges in C++.
(f) C++ Core Guidelines
• A set of guidelines for writing modern and maintainable C++ code, maintained
by Bjarne Stroustrup and Herb Sutter.
(g) Google C++ Style Guide
• A widely used style guide for writing clean and consistent C++ code.
164
(b) Clang/LLVM
• A modern compiler with excellent diagnostics and support for C++ standards.
• An IDE with robust support for C++ development, including debugging and
profiling tools.
• An online tool to explore and compare compiler outputs for C++ code.
(b) DeepSeek AI
(c) Gemini
• An AI-powered code completion tool that can assist with writing C++ code.
Additional Resources:
• Annual C++ conference with talks on advanced topics and modern C++
techniques.