ภาพรวม
ใน C++ อาร์เรย์สามารถ Initialize ได้ทั้งด้วยตัวแปร (Variables) และค่าคงที่ (Literal Values) ทั้งสองวิธีทำงานเหมือนกัน เพราะค่าจะถูกคัดลอกเข้าไปในอาร์เรย์
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = 3;
int arr[4];
arr[0] = a; // ใช้ตัวแปร
arr[1] = 8; // ใช้ค่าจริง (Literal)
arr[2] = b; // ใช้ตัวแปร
arr[3] = 2; // ใช้ค่าจริง (Literal)
cout << "The elements of array are: ";
for (int i = 0; i < 4; i++) {
cout << arr[i] << " ";
}
return 0;
}
ผลลัพธ์
The elements of array are: 5 8 3 2
วิธี Initialize อาร์เรย์แบบต่างๆ
1. Aggregate Initialization (C-Style)
int arr1[4] = {a, 8, b, 2}; // Mixed variables and literals
int arr2[4] = {5, 8, 3, 2}; // All literals
int arr3[4] = {a, b}; // Partial - เหลือเป็น 0
int arr4[4] = {}; // All zeros (C++11)
2. Designated Initializers (C++20)
int arr[4] = { [0] = a, [2] = b, [1] = 8, [3] = 2 };
3. std::array (Modern C++)
#include <array>
array<int, 4> arr = {a, 8, b, 2}; // Type-safe, มี .size(), รองรับ STL
4. std::vector (Dynamic Size)
#include <vector>
vector<int> vec = {a, 8, b, 2}; // ขนาดเปลี่ยนได้
vec.push_back(10); // เพิ่มได้
ความแตกต่าง Variable vs Literal
| ด้าน | Variable | Literal |
|---|---|---|
| ความยืดหยุ่น | ค่าเปลี่ยนได้ตอน Runtime | ค่าคงที่ Compile-time |
| ความอ่านง่าย | ชื่อตัวแปรอธิบายความหมายได้ | Magic Numbers (ควรหลีกเลี่ยง) |
| ประสิทธิภาพ | เท่ากัน (Copy Value) | เท่ากัน (Copy Value) |
| Debugging | ดูค่าตัวแปรได้ | ดูค่า Literal ได้เลย |
Best Practices
- ใช้
constหรือconstexprสำหรับ Literal Values ที่มีความหมาย - หลีกเลี่ยง Magic Numbers: แทน
arr[0] = 8;ใช้const int DEFAULT_VAL = 8; - เลือก
std::arrayสำหรับ Fixed-size,std::vectorสำหรับ Dynamic-size - Initialize ทุกตัวเสมอ (Uninitialized = Undefined Behavior)