In this article, we will discuss the signed char data type in C++.
Some properties of the signed char data type are:
- It is generally used to store 8-bit characters.
- Being a signed data type, it can store positive values as well as negative values.
- Size of 8 bits is occupied where 1 bit is used to store the sign of the value.
- A maximum value that can be stored in a signed char data type is typically 127, around 27 – 1(but is compiler dependent).
- The maximum and minimum value that can be stored in a signed char is stored as a constant in climits header file and can be named as SCHAR_MAX and SCHAR_MIN respectively.
- A minimum value that can be stored in a signed char data type is typically -128, i.e. around –27 (but is compiler dependent).
- In case of overflow or underflow of data type, the value is wrapped around. For example, if -128 is stored in a signed char data type and 1 is subtracted from it, the value in that variable will become equal to 127. Similarly, in the case of overflow, the value will round back to -128.
Below is the program to get the highest value that can be stored in signed char in C++:
C++
#include <climits>
#include <iostream>
using namespace std;
int main()
{
signed char valueFromLimits = SCHAR_MAX;
cout << "Maximum value from "
<< "climits constant: "
<< ( int )valueFromLimits
<< '\n' ;
valueFromLimits = SCHAR_MIN;
cout << "Minimum value from "
<< "climits constant: "
<< ( int )valueFromLimits
<< '\n' ;
signed char previous = -1;
signed char present = 0;
while (present > previous) {
previous++;
present++;
}
cout << "Maximum value using the "
<< "wrap around property: "
<< ( int )previous << '\n' ;
cout << "Maximum value using the "
<< "wrap around property: "
<< ( int )present;
return 0;
}
|
Output:
Maximum value from climits constant: 127
Minimum value from climits constant: -128
Maximum value using the wrap around property: 127
Maximum value using the wrap around property: -128