Variables & Data Types
Quick Notes
Section titled “Quick Notes”Biến cần có kiểu dữ liệu và tên.
Kích thước kiểu số phụ thuộc platform, nhưng sizeof(type) luôn cho biết số byte thật.
Dùng auto khi kiểu rõ từ vế phải, dùng const khi giá trị không đổi.
Syntax
Section titled “Syntax”int count = 10;double price = 9.99;char grade = 'A';bool ok = true;std::string name = "cpp";Type Table
Section titled “Type Table”| Type | Typical Size | Example |
|---|---|---|
short | 2 bytes | short x = 1; |
int | 4 bytes | int n = 42; |
long | 4 or 8 bytes | long v = 1000; |
long long | 8 bytes | long long id = 1LL; |
float | 4 bytes | float f = 1.5f; |
double | 8 bytes | double d = 1.5; |
bool | 1 byte | bool done = false; |
char | 1 byte | char c = 'x'; |
std::string | object | std::string s = "hi"; |
Example
Section titled “Example”#include <iostream>#include <string>
int main(){ const int maxUsers = 100; constexpr double pi = 3.1415926535; auto message = std::string{"ready"};
std::cout << maxUsers << ' ' << pi << ' ' << message << '\n';}Common Mistakes
Section titled “Common Mistakes”- Dùng
intcho giá trị có thể vượt quá khoảng 32-bit. - So sánh số thực bằng
==khi có sai số. - Dùng
autolàm code khó đọc ở biểu thức phức tạp.
Search Keywords
Section titled “Search Keywords”variables data types biến kiểu dữ liệu int double bool char string auto const constexpr