Maximum value of signed char 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++
// C++ program to obtain the maximum value // that we can store in signed char #include <climits> #include <iostream> using namespace std; // Driver Code int main() { // From the constant of climits // header file 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' ; // Using the wrap around property // of data types // Initialize two variables one // value with -1 as previous and // one with 0 as present signed char previous = -1; signed char present = 0; // Keep on increasing both values // until the present increases to // the max limit and wraps around to // the negative value i.e., present // becomes less the previous value 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
Contact Us