Back to blog

Phase 1: C++ Cơ Bản - Bắt Đầu với Modern C++

cppc++programmingfundamentalssystems
Phase 1: C++ Cơ Bản - Bắt Đầu với Modern C++

Chào mừng bạn đến với Phase 1 của lộ trình học Modern C++! Nếu bạn đến từ ngôn ngữ lập trình khác—Python, Java, Go, JavaScript, hoặc bất kỳ ngôn ngữ nào—bạn sẽ thấy nhiều khái niệm quen thuộc. Mục tiêu của phase này là giúp bạn làm quen với cú pháp Modern C++ và hiểu cách C++ tiếp cận các khái niệm lập trình cơ bản.

📖 Ghi chú: Đây là phiên bản tóm tắt tiếng Việt. Để xem nội dung đầy đủ với tất cả code examples và giải thích chi tiết, vui lòng đọc phiên bản tiếng Anh.

Thời gian: 1-2 tuần, 1-2 giờ mỗi ngày Yêu cầu: Kinh nghiệm lập trình với bất kỳ ngôn ngữ nào

Bạn Sẽ Học Được Gì

✅ Thiết lập môi trường phát triển C++ hoàn chỉnh
✅ Hiểu mô hình biên dịch C++ (preprocessor, compiler, linker)
✅ Sử dụng hệ thống kiểu dữ liệu C++ hiệu quả
✅ Viết code hiện đại với auto và decltype
✅ Hiểu references vs pointers
✅ Sử dụng const và constexpr đúng cách
✅ Viết functions với signatures phù hợp
✅ Làm việc với namespaces
✅ Xử lý I/O cơ bản và strings


Thiết Lập Môi Trường

1. Cài Đặt Compiler

C++ là ngôn ngữ biên dịch. Bạn cần compiler để chuyển source code thành chương trình thực thi.

Compilers phổ biến:

CompilerPlatformGhi chú
GCC (g++)Linux, macOS, WindowsPhổ biến nhất, hỗ trợ standards tốt
Clang (clang++)Linux, macOS, WindowsError messages tuyệt vời, nhanh
MSVCWindowsTích hợp Windows tốt nhất

Cài đặt theo Platform:

# Linux (Ubuntu/Debian)
sudo apt update
sudo apt install build-essential  # Cài GCC
 
# macOS
xcode-select --install
 
# Windows: Cài Visual Studio Community hoặc MSYS2

2. IDE/Editor

  • VS Code + Extensions (miễn phí, cross-platform)
  • CLion (paid, professional)
  • Visual Studio (Windows, miễn phí Community)

3. Chương Trình Đầu Tiên

#include <iostream>
 
int main() {
    std::cout << "Hello, Modern C++!" << std::endl;
    return 0;
}

Biên dịch và chạy:

g++ -std=c++20 -Wall -Wextra -Werror -o hello hello.cpp
./hello

4. Compiler Flags Quan Trọng

g++ -std=c++20 -Wall -Wextra -Wpedantic -Werror main.cpp -o main
 
# -std=c++20    Sử dụng C++20 standard
# -Wall         Bật "all" warnings phổ biến
# -Wextra       Bật extra warnings
# -Wpedantic    Tuân thủ strict standard
# -Werror       Treat warnings as errors (quan trọng!)

Mô Hình Biên Dịch C++

Source Code (.cpp) → Preprocessor → Compiler → Linker → Executable

1. Preprocessing (#include, #define):

  • Header files được copy-paste
  • Macros được expand

2. Compilation:

  • Type checking
  • Tạo object files (.o)

3. Linking:

  • Kết hợp object files
  • Tạo executable cuối cùng

Hệ Thống Kiểu Dữ Liệu C++

Kiểu Cơ Bản

#include <cstdint>  // Fixed-width types
 
// Integers
int count = 42;           // Thường 32 bits
int32_t standard = 42;    // Chính xác 32 bits (recommended)
int64_t large = 100000LL; // Chính xác 64 bits
 
// Floating-point
float price = 19.99f;     // 32-bit (có 'f' suffix)
double precise = 3.14159; // 64-bit (phổ biến nhất)
 
// Character và Boolean
char letter = 'A';        // 8 bits
bool isActive = true;     // true hoặc false

Type Inference với auto

auto count = 42;        // int
auto price = 19.99;     // double (KHÔNG phải float!)
auto message = "Hello"; // const char* (KHÔNG phải std::string!)
 
// auto hữu ích cho complex types
std::vector<std::pair<std::string, int>> data;
auto it = data.begin();  // Ngắn gọn hơn nhiều!

nullptr - The Null Pointer

Luôn dùng nullptr (C++11), không dùng NULL hoặc 0:

int* ptr = nullptr;  // Modern way (type-safe)
// int* ptr = NULL;  // Old way - tránh!
// int* ptr = 0;     // C way - tránh!

Variables và Constants

Khởi Tạo Biến

// Copy initialization (pre-C++11)
int a = 42;
 
// Brace initialization (C++11, recommended)
int c{42};
std::vector<int> nums{1, 2, 3, 4, 5};
 
// Brace initialization ngăn narrowing conversions
int x{3.14};  // Error! Không compile
int y = 3.14; // Compile nhưng truncate thầm lặng thành 3

const vs constexpr

// const - runtime constant, không thể modify
const int maxSize = 100;
 
// constexpr - compile-time constant
constexpr int size = 100;
constexpr double pi = 3.14159;
 
// constexpr functions
constexpr int square(int x) {
    return x * x;
}
 
constexpr int result = square(5);  // Computed at compile time: 25

Tóm tắt:

  • const - Không thể thay đổi (runtime hoặc compile time)
  • constexpr - Có thể tính toán lúc compile time
  • consteval (C++20) - PHẢI tính toán lúc compile time

References vs Pointers

References

Reference là alias cho biến đã tồn tại:

int value = 42;
int& ref = value;  // ref là alias cho value
 
ref = 100;  // Thay đổi value!
// ref PHẢI được khởi tạo
// ref KHÔNG thể được re-assign

Pointers

Pointer lưu địa chỉ bộ nhớ của biến:

int value = 42;
int* ptr = &value;  // ptr lưu địa chỉ của value
 
*ptr = 100;  // Thay đổi value qua pointer
ptr = nullptr;  // Có thể là null
ptr = &other;   // Có thể re-assign

Khi Nào Dùng Gì

Tính năngReferencePointer
Phải khởi tạoCóKhông
Có thể nullKhôngCó
Có thể re-assignKhôngCó

Guidelines:

  • Ưu tiên references khi không cần null
  • Dùng pointers khi null là trạng thái hợp lệ
  • Dùng const references cho read-only access
// Pass by const reference (read-only, không copy)
void process(const std::string& s);  // Phổ biến nhất cho "input" parameters

Control Flow

Conditional Statements

// if-else
if (score >= 90) {
    // ...
} else if (score >= 80) {
    // ...
} else {
    // ...
}
 
// if với initializer (C++17)
if (auto it = map.find(key); it != map.end()) {
    // it scoped to if-else block
}
 
// switch với initializer (C++17)
switch (auto value = getValue(); value) {
    case 1: /* ... */ break;
    default: break;
}

Loops

// for loop
for (int i = 0; i < 5; ++i) {
    std::cout << i << " ";
}
 
// Range-based for loop (C++11)
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (const auto& num : numbers) {
    std::cout << num << " ";
}
 
// while và do-while
while (condition) { /* ... */ }
do { /* ... */ } while (condition);

Functions

Basic Syntax

// Declaration và definition
int add(int a, int b) {
    return a + b;
}
 
// void function
void printMessage(const std::string& msg) {
    std::cout << msg << std::endl;
}

Parameter Passing

void byValue(int x);              // Copy
void byReference(int& x);         // Có thể modify
void byConstRef(const std::string& s);  // Read-only, hiệu quả
void byPointer(int* x);           // Có thể null

Modern Features

// Default arguments
void greet(const std::string& name, const std::string& greeting = "Hello");
 
// Function overloading
int add(int a, int b);
double add(double a, double b);
 
// constexpr functions
constexpr int factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}
 
// [[nodiscard]] attribute (C++17)
[[nodiscard]] int calculateResult();

Namespaces

namespace graphics {
    void draw() { /* ... */ }
}
 
namespace audio {
    void draw() { /* ... */ }
}
 
// Sử dụng
graphics::draw();
audio::draw();
 
// using declaration
using std::cout;
cout << "Hello";
 
// Nested namespaces (C++17)
namespace company::project::module {
    void function() { }
}

I/O và Strings

Console I/O

#include <iostream>
 
// Output
std::cout << "Hello, World!" << std::endl;
std::cout << "Name: " << name << ", Age: " << age << "\n";
 
// Input
int age;
std::cin >> age;
 
std::string line;
std::getline(std::cin, line);  // Đọc cả dòng

std::format và std::print (C++20/23)

#include <format>  // C++20
#include <print>   // C++23
 
// std::format
std::string msg = std::format("Name: {}, Age: {}", name, age);
 
// std::print (C++23)
std::print("Hello, {}!\n", name);
std::println("With automatic newline");

Strings

#include <string>
#include <string_view>
 
// std::string - sở hữu dữ liệu
std::string s = "Hello";
s += " World";
std::cout << s.length() << std::endl;
 
// std::string_view (C++17) - không sở hữu, tránh copy
void process(std::string_view sv);  // Hiệu quả cho read-only

Arrays

#include <array>
#include <vector>
 
// std::array - fixed-size (stack)
std::array<int, 5> arr = {1, 2, 3, 4, 5};
arr.size();  // Size is known
 
// std::vector - dynamic-size (heap)
std::vector<int> vec = {1, 2, 3};
vec.push_back(4);
vec.emplace_back(5);
 
// Tránh C-style arrays trong Modern C++!

Những Lỗi Thường Gặp Cần Tránh

1. Quên Khởi Tạo Biến

int x;  // Chứa garbage!
int y = 0;  // Luôn khởi tạo

2. Trả Reference đến Local Variable

int& dangerous() {
    int local = 42;
    return local;  // Dangling reference!
}

3. Bỏ Qua Compiler Warnings

# Luôn compile với warnings
g++ -Wall -Wextra -Werror main.cpp

Tóm Tắt và Key Takeaways

✅ Compilation: C++ được biên dịch (preprocessor → compiler → linker)
✅ Types: Dùng modern types (int32_t, std::string, std::vector)
✅ auto: Dùng cho complex types, explicit khi type không rõ ràng
✅ const vs constexpr: const = không thay đổi, constexpr = compile-time
✅ References: Ưu tiên references hơn pointers khi có thể
✅ nullptr: Luôn dùng nullptr, không dùng NULL hoặc 0
✅ Strings: Dùng std::string và std::string_view
✅ Arrays: Dùng std::array (fixed) hoặc std::vector (dynamic)
✅ Warnings: Luôn compile với -Wall -Wextra -Werror


Bước Tiếp Theo

Trong bài tiếp theo, chúng ta sẽ tìm hiểu Object-Oriented Programming trong C++:

  • Classes và objects
  • Constructors và destructors
  • RAII (Resource Acquisition Is Initialization)
  • Inheritance và polymorphism
  • Operator overloading

Chúc bạn học tập vui vẻ! 🚀


Bài viết này là một phần của Lộ Trình Học Modern C++.

Bài viết liên quan:


Để xem nội dung đầy đủ với tất cả code examples, vui lòng đọc phiên bản tiếng Anh.

📬 Đăng ký nhận bản tin

Nhận những bài viết mới nhất qua email mỗi tuần. Không spam, hủy đăng ký bất cứ lúc nào.

Chúng tôi tôn trọng quyền riêng tư của bạn. Hủy đăng ký bất cứ lúc nào.

💬 Comments

Đăng nhập để bình luận

Chúng tôi sẽ không đăng bất cứ điều gì mà không có sự cho phép của bạn.