Introduction
In the last lesson I've spoken a little about data types. Returning to the same example, imagine that you have a substance that needs to be kept in a special container. Let's think why some characteristics of that container matters.
Type
If you have a special container that can hold just one type of substance first of all it tells you that you can use it: to store that type of substance. With data types you tell the compiler/interpreter how you are going to use that piece of data.
If you declare a variable as a integer, you tell the compiler/interpreter that you will be using that variable as an integer.
The most common types are:
- integers
- floating-point numbers (real numbers)
- booleans (1 and 0)
- characters
Example
In C++, if you want to declare an integer, a fp number, a boolean and a character (a single one) you can do the following:int integ;
double fp_number;
bool bl;
char ch;
Size
The container may have different sizes. The bigger it is the more substance can it hold but also ocupies more space. The same is with data types. The bigger the data that it can hold the more memory it occupies. When you type a data type you tell the compiler/interpreter to reserve an ammount of memory.Now why size matters? Because your computer doesn't have an infinite ammount of memory and you also don't want to try to store data in a data type that won't be able to store it's size. If you try to do something like this funky stuff may happen, like if you try to put a big positive number in a type that won't support big numbers it may actually store a negative value.
Usually there are standards about this but size is dependent of the compiler/interpreter so those standards may not always apply.
Example
In C++ if you want to get the size of a data type you do:sizeof(data_type);
This will only get the size if you want to see it you need to print it somewhere:
std::cout << sizeof(data_type);
This will print on stdout (usaully console/terminal)
The standard would say that the size should be 2 bytes, meaning that it can hold a maximum value of 215.
The method of getting the maximum value is easy since 1 byte = 8 bits and a bit can hold either 1 or 0:
- Get the number of bytes a data type uses
- Rise 2 to the power of that number minus one
Modifires
Some programming languages have something called modifires that are some keywords that can alter the base type. This can make the data type to fit more precisely to your needs.Example
In C++ you have the next modifires:- signed - the date will have a sign (positive, negative)
- unsigned - the data will only be positive
- long- more memory
- short - less memory
- const - the variable can't be changed
- volatile - the variable can be changed (rarely used)