1.2 Data Types and Variables
Most values in a computer program have a type. The type tells the compiler what the value represents and what operations make sense for it.
C++ is a statically typed language: a variable must declare its type before use, which tells the compiler how much memory to allocate and what operations the variable can take part in.
Common C++ basic types include:
- Integer types:
int,short,long - Floating-point types:
float,double - Character type:
char - Boolean type:
bool
Value ranges of the types
Different types can represent different ranges. The table below lists typical sizes and ranges on common platforms (exact values may vary by platform and compiler).
| Type | Common size | Typical range |
|---|---|---|
char | 1 byte | -128 to 127 (or 0 to 255) |
short | 2 bytes | -32,768 to 32,767 |
int | 4 bytes | -2,147,483,648 to 2,147,483,647 |
long | 4 or 8 bytes | at least +/-2.1x10^9 (often +/-9.2x10^18 on 64-bit) |
float | 4 bytes | about +/-3.4x10^38 (about 7 significant digits) |
double | 8 bytes | about +/-1.7x10^308 (about 15 significant digits) |
bool | 1 byte | false or true |
<limits>, and floating-point details are available through <cfloat> or <limits>. When a value may exceed the range, choose a larger type to avoid overflow.Variables
A variable is a name used to store data. In C++, a variable must declare its type before use, and that type decides what kind of value it can hold.
int age = 18;
double height = 172.5;
char grade = 'A';
bool passed = true;Here, age holds an integer, so its type is int; height holds a decimal number, so its type is double; grade holds a single character, so its type is char; and passed holds either true or false. Note that a single character is wrapped in single quotes.
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.
int total_score = 95;C++ keywords
Keywords are reserved by C++ and cannot be used as ordinary variable names.
Common keywords include:
int,char,float,double,void,boolif,else,switch,case,defaultfor,while,do,break,continuereturn,sizeof,const,staticstruct,class,enum,namespace,template
Using a keyword as a variable name would make C++ unable to tell whether you mean a language feature or an ordinary value.