Signed and Unsigned are datatype modifiers which mostly use with integral type values to tell us about the sign of that value whether the value is a positive value or negative value.
- Signed type is used to represent negative or positive numbers including zero. The datatype like int, short, long, and long long are all signed values by default. Example: singed int x = -1;
- The Unsigned type is used to represent only values greater than or equal to zero. You can obtain the corresponding unsigned datatype by adding an unsigned keyword with the datatype. Example: unsigned int x = 4;
Note: Signed values have dedicated extra bits for storing the sign of the value.
Let's understand with one C++ example code of signed and unsigned values.
//C++ Example for signed and unsigned values #include<iostream> using namespace std; int main(){ unsigned int num = -1; int x = -1; cout<<num<<","<<x; return 0; }
4294967295,-1
In the above code, you can observe that when we try to store a negative value in an unsigned variable then in the output it is printing some random value, and the integer variable which is by default a signed variable can easily store a negative number.
When you try to store any negative value in an unsigned variable then that variable actually stores the 2's complement of the binary equivalent of that value. The 2's complement of -1 in 32-bit format will be equal to 4294967296 and that same value is printed in the output. (alert-success)
Basic Character Types
Unlike the other integer types, there are three distinct basic character types:
- char
- signed char
- unsigned char
Although there are three character types, there are only two representations and these are signed and unsigned. The char type uses one of these representations and it depends upon the compiler.
No comments:
Post a Comment