C++ Programming Series: Primitive Types

In the previous post, we discussed variables and a primitive type called as int. Primitive types are the basic types from which other complex things are derived. Like int, following are some other primitive types.

int int_var = 10;
char char_var = 'b';
bool bool_var = true;
float float_var = 24.12f;
double double_var = 248.123;

They have different sizes and they are calculated in bytes which is a term defined for measuring memory in computers. To find out the size of any type or variable, we can use sizeof().

cout << sizeof(int) << endl;
cout << sizeof(bool_var) << endl;
cout << sizeof(float) << endl;
cout << sizeof(double_var) << endl;

Size of int is 4 bytes, char is 1 byte, float 4 bytes and double 8 bytes. They have some value limits as well. For more information, click here.

char is the short form of character, stores a character and bool is the short form of boolean, can only have anyone of the two states, true and false.

float and double allows us to be precise in calculations. The latter one is more precise than the former one. float can have maximum of 7 decimal places whereas double can have maximum of 15 decimal places.

It is always better to use lesser memory or bytes of a computer. int is the most used variable type but it may be a waste if you just want to have it in a very small range of numbers. You can use short or long to increase or decrease the amount of memory allocated by it. For instance, if value of a regular int gets much greater than the limit, use long to have a much greater limit.

short int small_int = 20000;
long int large_int = 20000000;

By default, variables can have positive as well as negative values. There are many cases when negative values are not needed at all. Such variables having both positive and negative values are called as signed variables and those having positive values only are called as unsigned variables.

int i_am_signed_int1 = -100;
signed int i_am_signed_int2 = -250;
unsigned int i_am_unsigned_int3 = 500;

short, long, signed and unsigned aren’t only used with int but can also be used with some other primitive types.

Advertisements

One thought on “C++ Programming Series: Primitive Types

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s