Most values in a computer program have a type. The type tells C++ what the value represents and what operations make sense for it.
Common C++ types include:
- Integer types:
short,int,long, andlong long - Floating-point types:
float,double, andlong double - Character and Boolean types:
charandbool - Compound types: arrays, pointers, references, enums, classes, and
string
Variables
A variable is a named storage location. C++ is statically typed, so every variable declaration states what kind of data the variable can store.
For example, int num = 10; gives a type, name, and initial value, followed by a semicolon.
int num = 10;
cout << num << endl; // 10
double salary = 8232.56;
cout << salary << endl; // 8232.56Here, num is declared as int, while salary is declared as double. C++ checks later assignments against those types.
KNOWLEDGE QUIZ
Naming variables
Good variable names are clear and valid:
- Use letters, digits, and underscores, but do not start with a digit.
- Do not use C++ reserved keywords.
- Prefer meaningful English words.
Names like age, student_name, and total_score are easier to read than a or x1.
KNOWLEDGE QUIZ
C++ keywords
Keywords are reserved by C++ and cannot be used as ordinary variable names.
Common keywords include:
bool,char,int, anddoubleif,else,switch, andcasefor,while,break, andcontinueclass,struct,public, andprivatetry,catch,throw, andnamespace
Using a keyword as a variable name would make C++ unable to tell whether you mean a language feature or an ordinary value.
KNOWLEDGE QUIZ