Skip to content
Related Articles

Related Articles

Maximum value of unsigned char in C++
  • Last Updated : 18 Jan, 2021

In this article, we will discuss the maximum value of unsigned char data type in C++.

Some properties of the unsigned char data type are:

  • Being an unsigned data type, it can store only positive values.
  • Unsigned char data type in C++ is used to store 8-bit characters.
  • A maximum value that can be stored in an unsigned char data type is typically 255, around 28 – 1(but is compiler dependent).
  • The maximum value that can be stored in an unsigned char is stored as a constant in the <climits> header file, whose value can be used as UCHAR_MAX.
  • A minimum value that can be stored in an unsigned char data type is 0.
  • In case of overflow or underflow of data type, the value is wrapped around.
  • For example, if 0 is stored in an unsigned char data type and 1 is subtracted from it, the value in that variable will become equal to 255. Similarly, in the case of overflow, the value will round back to 0.

Below is the program to get the highest value that can be stored in unsigned char in C++:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to obtain the maximum
// value that can be stored in an
// unsigned char
  
#include <climits>
#include <iostream>
using namespace std;
  
// Function to find the maximum value
// stored in unsigned char
void maxUnsignedChar()
{
    // From the constant of climits
    // header file
    unsigned char valueFromLimits = UCHAR_MAX;
    cout << "Value from climits "
         << "constant : "
         << (int)valueFromLimits
         << "\n";
  
    // Using the wrap around property
    // of data types
  
    // Initialize a variable with
    // value 0
    unsigned char value = 0;
  
    // Subtract 1 from value since
    // unsigned data type cannot store
    // negative number, the value will
    // wrap around and store the maximum
    // value that we can store in it
    value = value - 1;
  
    cout << "Value using the wrap "
         << "around property : "
         << (int)value << "\n";
}
  
// Driver Code
int main()
{
    // Function call
    maxUnsignedChar();
  
    return 0;
}

chevron_right


Output:

Value from climits constant : 255
Value using the wrap around property : 255

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :