Search code examples
ccharsignedunsigned-char

Difference between in signed and unsigned char in c


What is the difference between signed and unsigned char in C ? When I tried to run the following code without unsigned it entered an infinite loop as the range of signed char is up to 127 (Why is it signed by default ?). But when I added unsigned (whose range is up to 255) it works fine. What's the reason ?

#include <stdio.h>

int main() {
    unsigned char x;
    x = 0;
    while (x <= 225) {
         printf("%c=%d\n", x, x);
         x = x + 1;
    }
    return 0;
}

Solution

  • There's no dedicated "character type" in C language. char is an integer type, same (in that regard) as int, short and other integer types.

    • They are both integer types.
    • They have same size(one btye).

    If you are using numbers as char

    • Signed char, which gives you at least the -127 to 127 range. (-128 to 127 is common)
    • Unsigned char, which gives you at least the 0 to 255 range.

    From 3.9.1 Fundamental types

    Plain char, signed char, and unsigned char are three distinct types. A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements (3.11); that is, they have the same object representation.