-1

To find out the range of integer values for a standard 8-bit char, I ran the following code:

int counter = 0;

for (int i = -300; i <= 300; i++)
{
    char c = static_cast<char> (i);

    int num = static_cast<int> (c);

    if (num == i)
    {
        counter ++;
    }

    else
    {
        cout << "Bad:  " << i << "\n";
    }
}

cout << "\n" << counter;

I ended up seeing a value of 256 for counter, which makes sense. However, on the list of "Bad" numbers (i.e., numbers that chars don't store), I found that the greatest Bad negative number was -129, while the smallest Bad positive number was 128.

From this test, it seems like chars only store integer values from -128 to 127. Is this conclusion correct, or am I missing something? Because I always figured chars stored integer values from 0 to 255.

  • 3
    Can be either, it's implementation defined. `char` can even have more than eight bits, but not fewer. – Baum mit Augen Dec 28 '17 at 23:04
  • 2
    `char` is `signed char` in your implementation, so there are negative and positive values. Use `unsigned char` and they'll start at `0`. – Barmar Dec 28 '17 at 23:09
  • 1
    There exist `signed char`, `unsigned char` and `char`. It is implementation defined, if char is signed or unsigned. –  Dec 28 '17 at 23:09
  • @SpencerWieczorek Oops, my dupe was for C, not C++. What's the rule for C++? – Barmar Dec 28 '17 at 23:12
  • It's the same for C++ @Barmar. All the basic integer stuff is simply inherited from C for compatibility, and it's not going to change either. – Baum mit Augen Dec 28 '17 at 23:13
  • See https://stackoverflow.com/questions/17097537/why-is-char-signed-by-default-in-c – Barmar Dec 28 '17 at 23:13

1 Answers1

1

Although implementation defined, for the most part - yes it is normal as your implementation defines char as a signed char. You can use the CHAR_MIN and CHAR_MAX macros to print out the minimum and maximum values of type char:

#include <iostream>
#include <cstdint>

int main() {
    std::cout << CHAR_MIN << '\n';
    std::cout << CHAR_MAX << '\n';
}

Or using the std::numeric_limits class template:

#include <iostream>
#include <limits>

int main() {
    std::cout << static_cast<int>(std::numeric_limits<char>::min()) << '\n';
    std::cout << static_cast<int>(std::numeric_limits<char>::max()) << '\n';
}

As for the 0..255 range that is the unsigned char type. Min value is 0 and max should be 255. It can be printed out using:

std::cout << UCHAR_MAX;

Whether the type is signed or not can be checked via:

std::numeric_limits<char>::is_signed;

Excerpt from the char type reference:

char - type for character representation which can be most efficiently processed on the target system (has the same representation and alignment as either signed char or unsigned char, but is always a distinct type).

Ron
  • 14,674
  • 4
  • 34
  • 47