Social Icons

9 July 2012

0 Data type modifiers in C

We have so far learned about the fundamental data types, why they are used, their default sizes and values. Now let us understand the need for data type modifiers and the way they can be used.

Let us consider an example of a program, which will accept an age from the user to do some processing. Because the age is represented in numbers, so we will have to use the integer data type int. We all know that even under exceptional case an age of a person cannot exceed more than 150. Now, that we are using an integer data type it occupies 2 Bytes of memory, which would not be required to represent the value 150. Instead the value 150 could easily be saved in an integer of 1 Byte in size, but the default size of an integer is 2 Bytes. So we have a problem here.

Well, not that we can't solve. To override the default nature of a data type, C has provided us with data type modifiers as follows:


signed
By default all data types are declared as signed. Signed means that the data type is capable of storing negative values.


unsigned
To modify a data type's behavior so that it can only store positive values, we require to use the data type unsigned.

For example, if we were to declare a variable age, we know that an age cannot be represented by negative values and hence, we can modify the default behavior of the int data type as follows:

unsigned int age;

This declaration allows the age variable to store only positive values. An immediate effect is that the range changes from (-32768 to 32767) to (0 to 65536)

long
Many times in our programs we would want to store values beyond the storage capacity of the basic data types. In such cases we use the data type modifier long. This doubles the storage capacity of the data type being used. E.g. long int annual salary will make the storage capacity of variable annual salary to 4 bytes.

The exception to this is long double, which modifies the size of the double data type to 10 bytes. Please note that in some compilers this has no effect.


short
If long data type modifier doubles the size, short on the other hand reduces the size of the data type to half. Please refer to the example of age variable to explain the concept of data type modifiers. The same will be achieved by providing the declaration of age as follows:

short int age;

This declaration above, will provide the variable age with only 1 byte and its data range will be from -128 to 127.

0 comments:

Post a Comment

Hey this is a test comment

Related Posts Plugin for WordPress, Blogger...