C++ supports many data types that represent the size and kind of values being stored in memory.
The size of a given data type is measured in bytes:
|Data Type||Memory Size|
int is a type for storing integer (whole) numbers. An integer usually requires 4 bytes of memory space and ranges from -231 to 231.
int year = 1991;int age = 28;
double type stores floating point (decimal) numbers. These variables usually require 8 bytes of memory space.
double price = 8.99;double pi = 3.14159;
bool type stores boolean values of
false. These values usually require 1 byte of memory space.
bool organ_donor = true;bool late_to_work = false;
char type stores individual characters, wrapped in single quotes
'. Characters usually require 1 byte of memory space and range from -128 to 127.
char grade = 'A';char punctuation = '?';
Strings are character sequences wrapped in double quotes (e.g.,
std::string type is used for storing text strings.
std::string message = "good nite";std::string user = "@sonnynomnom";
As the name implies, datatype modifiers are used with built-in data types to modify the length of data that a particular data type can hold. Data type modifiers in C++ are:
Constant variables cannot be changed by the program during execution. The
const keyword can be added before the data type to make the variable immutable:
const double quarter = 0.25;// and now variable quarter can only be 0.25
A type cast is basically a conversion from one type to another.
(type) value means “convert value to type.” For example:
double weight1;int weight2;weight1 = 154.49;// assigned a double valueweight2 = (int) weight1;// weight2 is now 154 due to explicit type conversionint weight3 = weight1;// weight3 is also 154 due to implicit conversion by the compiler
Note: Going from a double to an int simply removes the decimal. There’s no rounding involved.
Alternatively, there is a safer version of casting in C++ called
static_cast that can be used. Performed at compile time,
static_cast offers better debugging and safer code:
double weight1 = 122.03;int weight2 = static_cast<int>(weight1);std::cout << weight2 << std::endl;// Output: 122
Note: Not all types can be converted:
std::string s = static_cast<std::string>(weight2);
This throws the following error upon compilation:
no known conversion for argument 1 from ‘int’ to ‘std::__cxx11::basic_string<char>&&’