In C and C++, sign qualifiers determine whether a variable can store both positive and negative values or only non-negative values. These qualifiers are mainly used with integer types and influence the range of values a variable can hold. The two sign qualifiers are:
signed
unsigned
1. signed
Qualifier
The signed
qualifier indicates that a variable can hold both positive and negative values. In most systems, integers are signed by default, meaning that a variable of type int
can store values in a range that includes both negative and positive numbers.
- Size: Typically, a
signed
integer uses the first bit (most significant bit) as a sign bit (0 for positive and 1 for negative). This reduces the maximum value range since one bit is reserved for the sign. - Range:
- For a
signed int
(typically 4 bytes or 32 bits):- Range: -2,147,483,648 to 2,147,483,647.
- For a
signed short
(typically 2 bytes or 16 bits):- Range: -32,768 to 32,767.
- For a
Example:
signed int a = -10; // Can hold negative and positive values
signed short b = 32767; // Maximum value for signed short
By default, if you just write int
or short
, the system assumes signed
unless explicitly specified otherwise.
2. unsigned
Qualifier
The unsigned
qualifier restricts a variable to hold only non-negative (positive or zero) values. Since there’s no need to reserve a bit for the sign, the total number of positive values that can be stored increases, effectively doubling the maximum positive range.
- Size: All bits are used to represent the magnitude of the number, allowing for a larger range of non-negative values.
- Range:
- For an
unsigned int
(typically 4 bytes or 32 bits):- Range: 0 to 4,294,967,295.
- For an
unsigned short
(typically 2 bytes or 16 bits):- Range: 0 to 65,535.
- For an
unsigned int c = 5000; // Cannot hold negative values
unsigned short d = 65535; // Maximum value for unsigned short
Using unsigned
is helpful when you know that your variable will only hold non-negative values, such as array indices, file sizes, or object counts. It ensures that the variable never goes below zero, making errors easier to catch.