Day02-Variables and Data Types - Part 1
variable ក្នុង C++ គឺជាទីតាំង memory ដែលមានឈ្មោះប្រើដើម្បី store data ដែលអាច modified ក្នុងអំឡុងពេល execution នៃ program មួយ។ វាដើរតួជា container សម្រាប់ holding value នៃ data type ជាក់លាក់មួយ ដូចជា numbers, characters, ឬ strings។ variable ត្រូវតែ declared មុនពេលប្រើ ដោយ specifying type និង name របស់វា ហើយវាអាច optionally initialized ជាមួយ value មួយ។
គន្លឹះសំខាន់ៗនៃ variable ក្នុង C++:
- Declaration: អ្នក specifying data type តាមដោយ variable name (e.g., int age;)។ variable name ត្រូវ start with a letter or underscore, អាច include letters/numbers/underscores, និង are case-sensitive.
- Initialization: Assigning initial value (e.g., int age = 25;).
- Data Types: Common built-in types include:
- int (integers, e.g., 42)
- float or double (floating-point numbers, e.g., 3.14)
- char (single characters, e.g., 'A')
- bool (true/false)
- string (text, requires #include <string> header)
- Scope: variable អាច be local (inside a function/block) ឬ global (outside functions).
- Mutability: Most variable អាច changed after declaration, unless declared as const (constant).
Example:
នេះគឺជា simple C++ program ដែល declares, initializes, និង uses variable ដើម្បី calculate sum នៃ numbers ពីរ:
#include <iostream> // សម្រាប់ input/output
int main() {
// ប្រកាស និង initialize variable
int num1 = 10; // Integer variable
int num2 = 20; // Another integer variable
int sum; // ប្រកាស without initialization
sum = num1 + num2; // Assign value by performing addition
// Output the result
cout << "ផលបូកនៃ " << num1 << " និង " << num2 << " គឺ: " << sum << endl;
return 0;
}
ការពន្យល់:
- int num1 = 10; declares variable num1 of type int និង initializes វាទៅ 10.
- យើង perform an operation (sum = num1 + num2;) to store new value in sum.
- program prints: "ផលបូកនៃ 10 និង 20 គឺ: 30"
- Compile និង run this using C++ compiler (e.g., g++), និងវាបង្ហាញ how variable hold និង manipulate data.
variable គឺ fundamental to programming, allowing dynamic data handling in loops, conditions, និង functions. For more advanced topics, explore arrays, pointers, or user-defined types like classes.