Add to Technorati Favorites

More On Variables

Welcome back. We will continue with variables. Variables are stored in form of 0's and 1's in Random Access Memory (RAM) of computer when program is in execution state. Memory was a precious resource sometimes back (may not be not that precious now). So, its efficient utilization is very important. Allocating same amount of memory for every variable is not a good idea. Like there are clothes to fit every size, there are data-types that can be associated with variables which determines:
  • How much memory to be allocated for variable
  • How to interpret the 0's and 1's representing the memory
  • What are the permissible operations on that variable
Let us see what are the different built-in primitive data types available in C++:

bool (1 byte) : True/False
char (1 byte) : character or small number
short (2 bytes) : short integer
int (4 bytes) : integer
long (4 byets) : long integer
float (4 bytes) : floating point number
double (8 bytes) : double precision floating point number
long double (8 bytes) : double precision floating point number
wchar_t (2 or 4 bytes): to support unicode characters

How much memory a variable/ data-type uses depends on:
  • Platform and/or
  • Compiler
Sizes listed above are on 32-bit windows machine and MS VC++ compiler.

To know these sizes on your computing environment, you can use following operator:
sizeof(data-type or variable name)
For example, sizeof(bool) will return 1 byte

How big or small number can be represented with given data type can be computed using following formula:

-2 (raised to power 'n-1') to 2 (raised to power 'n-1') -1

where 'n' is number of bits. So, a variable of short data-type ( 2bytes = 16 bits) can represent values from: -32768 to32767

If your number is positive the range formula becomes:
0 to 2 (raised to power 'n').

To tell compiler that your variable will have positive values only, you have to use unsigned modifier.

For example, unsigned short weight;
Now weight can take values from 0 to 65535

Out of primitive data-types, composite ones can be declared and used. Composite data types in C++ include:

  • Arrays
  • Structures
  • Unions
  • Classes
  • List, Map, Set etc. supported by Standard Template Library (STL)
You will learn more about composite data types and STL in later posts.
This is all for today. We will take up operators in next post.

No comments: