Variables are used for storing data during program execution.
Depending on what data you need to store there are several kinds of built-in data types. These are often called fundamental data types or primitives. The integer (whole number) types are short, int, long, and long long. The float, double and long double types are floating-point (real number) types. The char type holds a single character and the bool type contains either a true or false value.
Data Type | Size (byte) | Description |
---|---|---|
char | 1 | Integer or character |
short | 2 | |
int | 4 | Integer |
long | 4 or 8 | |
long long | 8 | |
float | 4 | |
double | 8 | Floating-point number |
long double | 8 or 16 | |
bool | 1 | Boolean value |
In C++, the exact size and range of data types are not fixed. Instead they are dependent on the system for which the program is compiled. The sizes shown in the table above are those found on most 32-bit systems and are given in C++ bytes. A byte in C++ is the minimum addressable unit of memory, which is guaranteed to be at least 8 bits, but might also be 16 or 32 bits depending on the system. By definition, a char in C++ is 1 byte in size. Furthermore, the int type will have the same size as the processor’s word size, so for a 32-bit system the integers will be 32 bits in size. Each integer type in the table must also be at least as large as the one preceding it. The same applies to floating-point types where each one must provide at least as much precision as the preceding one.
To declare (create) a variable you start with the data type you want the variable to hold followed by an identifier, which is the name of the variable. The name can consist of letters, numbers and underscores, but it cannot start with a number. It also cannot contain spaces or special characters and must not be a reserved keyword.
int myInt; // correct int _myInt32; // correct int 32Int; // incorrect (starts with number) int Int 32; // incorrect (contains space) int Int@32; // incorrect (contains special character) int new; // incorrect (reserved keyword)
To assign a value to a declared variable the equal sign is used, which is called the assignment operator (=).
myInt = 50;
The declaration and assignment can be combined into a single statement. When a variable is assigned a value it then becomes defined.
int myInt = 50;
At the same time that the variable is declared there is an alternative way of assigning, or initializing, it by enclosing the value in parentheses. This is known as constructor initialization and is equivalent to the statement above.
int myAlt (50);
If you need to create more than one variable of the same type there is a shorthand way of doing it using the comma operator (,).
int x = 1, y = 2, z;
Once a variable has been defined (declared and assigned), you can use it by simply referencing the variable’s name: for example, to print it.
std::cout << x << y; // “12”
The scope of a variable refers to the region of code within which it is possible to use that variable. Variables in C++ may be declared both globally and locally. A global variable is declared outside of any code blocks and is accessible from anywhere after it has been declared. A local variable, on the other hand, is declared inside of a function and will only be accessible within that function after it has been declared. The lifetime of a local variable is also limited. A global variable will remain allocated for the duration of the program, while a local variable will be destroyed when its function has finished executing.
int globalVar; // global variable int main() { int localVar; } // local variable
The default values for these variables are also different. Global variables are automatically initialized to zero by the compiler, whereas local variables are not initialized at all. Uninitialized local variables will therefore contain whatever garbage is already present in that memory location.
int globalVar; // initialized to 0 int main() { int localVar; // uninitialized }
Using uninitialized variables is a common programming mistake that can produce unexpected results. It is therefore a good idea to always give your local variables an initial value when they are declared.
int main() { int localVar = 0; // initialized to 0 }
There are four integer types you can use depending on how large a number you need the variable to hold.
char myChar = 0; // -128 to +127 short myShort = 0; // -32768 to +32767 int myInt = 0; // -2^31 to +2^31-1 long myLong = 0; // -2^31 to +2^31-1
C++11 standardized a fifth integer type, long long, which is guaranteed to be at least 64-bits large. Many compilers started to support this data type well before the C++11 standard was complete, including the Microsoft C++ compiler.
long long myL2 = 0; // -2^63 to +2^63-1
To determine the exact size of a data type you can use the sizeof operator. This operator returns the number of bytes that a data type occupies in the system you are compiling for.
std::cout << sizeof(myChar) // 1 byte (per definition) << sizeof(myShort) // 2 << sizeof(myInt) // 4 << sizeof(myLong) // 4 << sizeof(myL2); // 8
Fixed-sized integer types were added in C++11. These types belong to the std namespace and can be included through the cstdint standard library header.
#include <cstdint> using namespace std; int8_t myInt8 = 0; // 8 bits int16_t myInt16 = 0; // 16 bits int32_t myInt32 = 0; // 32 bits int64_t myInt64 = 0; // 64 bits
By default, all the number types in Microsoft C++ are signed and may therefore contain both positive and negative values. To explicitly declare a variable as signed the signed keyword can be used.
signed char myChar = 0; // -128 to +127 signed short myShort = 0; // -32768 to +32767 signed int myInt = 0; // -2^31 to +2^31-1 signed long myLong = 0; // -2^31 to +2^31-1 signed long long myL2= 0; // -2^63 to +2^63-1
If you only need to store positive values you can declare integer types as unsigned to double their upper range.
unsigned char myChar = 0; // 0 to 255 unsigned short myShort = 0; // 0 to 65535 unsigned int myInt = 0; // 0 to 2^32-1 unsigned long myLong = 0; // 0 to 2^32-1 unsigned long long myL2= 0; // 0 to 2^64-1
The signed and unsigned keywords may be used as standalone types, which are short for signed int and unsigned int.
unsigned uInt; // unsigned int signed sInt; // signed int
Similarly, the short and long data types are abbreviations of short int and long int.
short myShort; // short int long myLong; // long int
In addition to standard decimal notation, integers can also be assigned by using octal or hexadecimal notation. Octal literals use the prefix “0” and hexadecimal literals start with “0x.” Both numbers below represent the same number, which in decimal notation is 50.
int myOct = 062; // octal notation (0) int myHex = 0x32; // hexadecimal notation (0x)
As of C++14 there is a binary notation, which uses “0b” as its prefix. This version of the standard also added a digit separator (') which can make it easier to read long numbers. The binary number below represents 50 in decimal notation.
int myBin = 0b0011'0010; // binary notation (0b)
The floating-point types can store real numbers with different levels of precision.
float myFloat; // ~7 digits double myDouble; // ~15 digits long double myLongDouble; // typically same as double
The precision shown above refers to the total number of digits in the number. A float can accurately represent about 7 digits, whereas a double can handle around 15 of them. Trying to assign more than 7 digits to a float means that the least significant digits will get rounded off.
myFloat = 12345.678; // rounded to 12345.68
Floats and doubles can be assigned by using either decimal or exponential notation. Exponential (scientific) notation is used by adding E or e followed by the decimal exponent.
myFloat = 3e2; // 3*10^2 = 300
An integer literal (constant) is normally treated as an int by the compiler, or a larger type if needed to fit the value. Suffixes can be added to the literal to change this evaluation. With integers the suffix can be a combination of U and L, for unsigned and long respectively. C++11 also added the LL suffix for the long long type. The order and casing of these letters do not matter.
int i = 10; long l = 10L; unsigned long ul = 10UL;
A floating-point literal is treated as a double unless otherwise specified. The F or f suffix can be used to specify that a literal is of the float type instead. Likewise, the L or l suffix specifies the long double type.
float f = 1.23F; double d = 1.23; long double ld = 1.23L;
The compiler implicitly converts literals to whichever type is necessary, so this type distinction for literals is usually not necessary. If the F suffix is left out when assigning to a float variable, the compiler may give a warning since the conversion from double to float involves a loss of precision.
The char type is commonly used to represent ASCII characters. Such character constants are enclosed in single quotes and can be stored in a variable of char type.
char c = 'x'; // assigns 120 (ASCII for 'x')
The conversion between the number stored in the char and the character shown when the char is printed occurs automatically.
std::cout << c; // prints 'x'
For another integer type to be displayed as a character it has to be explicitly cast to char. An explicit cast is performed by placing the desired data type in parentheses before the variable or constant that is to be converted.
int i = c; // assigns 120 std::cout << i; // prints 120 std::cout << (char)i; // prints 'x'
The bool type can store a Boolean value, which is a value that can only be either true or false. These values are specified with the true and false keywords.
bool b = false; // true or false value
All Rights Reserved. © 2024 BookOfNetwork