Type modifiers in C are used as a prefix to the datatypes to re-define the size & range of the datatype.
Syntax:
<Type_modifier> SPACE <Datatype> SPACE <Variable_name>
Example: unsigned int a;
Based on their usage, type modifiers in C are classified into two categories:
Category 1:
- Signed
- Unsigned
Category 2:
- Short
- Long
In this article, we will see the category-1 type modifiers.
The most important thing that we need to keep in mind is, both signed and unsigned type modifiers are applied only to data types of the integer family i.e. char and int.
Signed type modifier in C:
For an int data type, if we don’t mention the type modifier, By default it will be considered as a signed type modifier.
- The variable with a signed type modifier is capable of storing both positive and negative values.
- In a variable with a 32-bit integer data type, 1-bit (Most significant bit) is reserved for sign & the remaining 31-bits are used for data.
- If the most significant bit contains ‘0’ then it means that the variable contains a positive value & 1 specifies that the variable contains a negative value.
How to calculate the range of any datatype with signed type modifier:
The range of the data type with the signed type modifier is -2 (power (N-1)) to +2 (power (N-1))-1
. Here N is the no of bits allocated for the data type.
- The ‘N’ value can be calculated by using N = 8 x the Size of the data type.
Unsigned type modifier in C:
For a char data type, if we don’t mention the type modifier, By default it will be considered as an unsigned type modifier.
- The variable with an unsigned type modifier is capable of storing only positive values.
- No sign bit is reserved for variables declared with an unsigned type modifier. All 32 bits contain data.
Formulae to calculate the range of any datatype with an unsigned type modifier:
The range of the data type with an unsigned type modifier is 0 to +2 (power (N))-1
. Here N is the no of bits allocated for the data type.
- ‘N’ value can be calculated by using formulae
N = 8 x Size of the data type
.
Example program on signed and unsigned type modifier
#include <stdio.h>int main(){ signed int a = -10; // can able to hold both +ve and -ve values. unsigned int b = 20; // can able to store only +ve values. printf("%d %u", a, b); return 0;}
Explanation:
- ‘
%u
‘ is a format specifier used in printf to specify, the variable is of type unsigned integer. - In the above example, the variable ‘
a
‘ is capable of holding both positive and negative values because 1-bit is reserved for the sign and variable ‘b’ is capable of storing only positive values. - By default, int uses signed type modifier and char uses unsigned type modifier.
In our next article, we will discuss the category-2 type modifiers. i.e. short and long.