C++ short tutorial
C++
C++ is far from dead; it's constantly evolving and improving, making it a powerful and versatile language for everything from games to operating systems to high-performance computing. The new syntax makes code cleaner, more expressive, and easier to manage.
What is C++?
Think of C++ as a powerful "Swiss Army Knife" programming language. It gives you a lot of control over your computer's resources (like memory) while also offering high-level features like object-oriented programming (OOP) and standard libraries. It's a great blend of low-level hardware interaction and high-level application development.
Why Learn Modern C++ (like C++23)?
C++23 introduces features that aim to improve:
- Readability: Making code easier to understand.
- Conciseness: Writing less code to achieve the same result.
- Safety: Reducing common errors.
- Modernity: Aligning C++ with current software development practices.
Let's Start with "Hello, World!"
We'll begin with the classic program.
#include <iostream> // Include the input/output library
#include <string> // Include the string library
// The main function - where program execution begins
int main() {
// Declare a string variable
std::string message = "Hello, C++23 World!";
// Print the message to the console
std::cout << message << std::endl;
// Return 0 to indicate successful execution
return 0;
}
Explanation:
#include <iostream>
: This line tells the compiler to include theiostream
library, which gives us tools for input and output (like printing to the screen).#include <string>
: This includes thestring
library, which allows us to work with text strings (std::string
).int main() { ... }
: This is the main function. Every C++ program must have amain
function. Theint
indicates that it will return an integer value (usually 0 for success).std::string message = "Hello, C++23 World!";
: This declares a variable namedmessage
of typestd::string
and initializes it with the text "Hello, C++23 World!".std::cout << message << std::endl;
: This is where the printing happens.std::cout
is the standard output stream (usually the console).<<
is the "insertion operator," used to send data to the stream.message
is the variable we want to print.std::endl
inserts a newline character and flushes the output buffer.
return 0;
: Indicates that the program finished successfully.
Cool C++23 Features (and some earlier modern ones too!):
1. auto
Keyword (C++11, but still very useful!):
auto
lets the compiler figure out the type of a variable automatically based on its initialization. It's great for reducing boilerplate.
#include <iostream>
#include <vector>
#include <string>
int main() {
auto number = 10; // Compiler figures out 'number' is an int
auto pi = 3.14159; // Compiler figures out 'pi' is a double
auto name = "Alice"; // Compiler figures out 'name' is a const char*
auto numbers = {1, 2, 3}; // Compiler figures out 'numbers' is an initializer_list<int>
std::cout << "Number: " << number << std::endl;
std::cout << "Pi: " << pi << std::endl;
std::cout << "Name: " << name << std::endl;
return 0;
}
2. Range-Based For Loops (C++11):
A much cleaner way to iterate over containers (like vectors or arrays).
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> fruits = {"apple", "banana", "cherry"};
std::cout << "My favorite fruits:" << std::endl;
for (const auto& fruit : fruits) { // 'const auto&' for efficiency and safety
std::cout << "- " << fruit << std::endl;
}
return 0;
}
for (const auto& fruit : fruits)
: This iterates through each element (fruit
) in thefruits
vector.const auto&
meansfruit
is a constant reference to each element, avoiding copies and preventing accidental modification.
3. Lambda Expressions (C++11):
Small, anonymous functions you can define right where you need them. Great for passing functions to other functions.
#include <iostream>
#include <vector>
#include <algorithm> // For std::sort
int main() {
std::vector<int> numbers = {5, 1, 4, 2, 8};
// Sort the vector in descending order using a lambda function
std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
return a > b; // Custom comparison for descending order
});
std::cout << "Sorted numbers (descending):" << std::endl;
for (const auto& num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
[](int a, int b) { return a > b; }
: This is the lambda function.[]
: The capture list (empty here, meaning it doesn''t capture variables from the surrounding scope).(int a, int b)
: The parameters the lambda takes.{ return a > b; }
: The body of the lambda.
4. std::span
(C++20):
A non-owning view of a contiguous sequence of objects (like an array or vector). It''s efficient for passing parts of containers without copying.
#include <iostream>
#include <vector>
#include <span> // Include the span header
void print_elements(std::span<const int> data) {
std::cout << "Span elements: ";
for (int element : data) {
std::cout << element << " ";
}
std::cout << std::endl;
}
int main() {
std::vector<int> numbers = {10, 20, 30, 40, 50};
// Create a span over the entire vector
std::span<const int> full_span(numbers);
print_elements(full_span);
// Create a span over the first 3 elements
std::span<const int> first_three(numbers.data(), 3);
print_elements(first_three);
// Create a span over elements from index 1 to 3 (inclusive)
std::span<const int> middle_part(numbers.data() + 1, 3);
print_elements(middle_part);
return 0;
}
5. std::print
(C++23):
A modern, type-safe way to print output, similar to Python's print
. It's often more efficient than std::cout
for simple cases.
#include <iostream>
#include <string>
#include <print> // Include the print header (C++23)
int main() {
std::string name = "Charlie";
int age = 30;
double score = 95.5;
// Use std::print for formatted output
std::print("Hello, {}! You are {} years old.\n", name, age);
std::print("Your score is {:.1f}.\n", score); // Format to 1 decimal place
return 0;
}
std::print(...)
: Uses{}
as placeholders for arguments, similar to Python's f-strings or C++'sprintf
.
6. Ranges (C++20, enhanced in C++23):
A powerful way to work with sequences of elements in a functional style. You can chain operations like filtering, transforming, and sorting easily.
#include <iostream>
#include <vector>
#include <ranges> // Include the ranges header
#include <algorithm>
#include <print>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Create a view that filters for even numbers and squares them
auto even_squares = numbers
| std::views::filter([](int n) { return n % 2 == 0; }) // Filter for even numbers
| std::views::transform([](int n) { return n * n; }); // Square the even numbers
std::print("Even squares: ");
for (int sq : even_squares) {
std::print("{} ", sq);
}
std::print("\n");
return 0;
}
std::views::filter(...)
: Creates a view that only includes elements for which the lambda returnstrue
.std::views::transform(...)
: Creates a view that applies the lambda to each element.|
: The "pipe" operator, used to chain range views.
Compiling and Running:
To compile this code, you''ll need a modern C++ compiler that supports C++23 (like GCC 13 or later, Clang 16 or later, or MSVC with recent updates).
Using GCC:
g++ -std=c++23 your_program.cpp -o your_program
./your_program
Using Clang:
clang++ -std=c++23 your_program.cpp -o your_program
./your_program
Using MSVC (Command Prompt):
cl /EHsc /std:c++23 your_program.cpp
your_program.exe
Conclusion:
C++ is a powerful and flexible language, and modern features like auto
, range-based for loops, lambdas, std::span
, std::print
, and ranges (especially C++20 and C++23) make it significantly more expressive, readable, and enjoyable to use. Keep exploring these features, experiment with them, and you'll find that C++ is far from dead – it's just getting better and better! Happy coding!