C++ – Variables and Datatypes
Variables let you store values dynamically.
Declare a variable
First you have to declare the variable type, the most used are:
Character types
– char Exactly one byte in size. At least 8 bits.
– char16_t Not smaller than char. At least 16 bits.
– char32_t Not smaller than char16_t. At least 32 bits.
– wchar_t Can represent the largest supported character set.
Integer types (signed)
– signed char Same size as char. At least 8 bits.
– signed short int Not smaller than char. At least 16 bits.
– signed int Not smaller than short. At least 16 bits.
– signed long int Not smaller than int. At least 32 bits.
– signed long long int Not smaller than long. At least 64 bits.
Integer types (unsigned) Same size as their signed counterparts
– unsigned char
– unsigned short int
– unsigned int
– unsigned long int
– unsigned long long int
Floating-point types
– float
– double Precision not less than float
– long double Precision not less than double
Boolean type
– bool
Void type
– void no storage
Null pointer
– decltype(nullptr)
Declaration of variables sample:
#include <iostream> using namespace std; int main () { // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << result; // terminate the program: return 0; }
Initialization
Initialization of variables, the initial value of a variable:
#include <iostream> using namespace std; int main () { // initialization of variables int a=5; // initial value: 5 int b(3); // initial value: 3 int c{2}; // initial value: 2 int result; // initial value undetermined a = a + b; result = a - c; cout << result; // the result is 6 return 0; }
Type deduction: auto and decltype
// auto int foo = 0; auto bar = foo; // the same as: int bar = foo; //decltype int foo = 0; decltype(foo) bar; // the same as: int bar;