Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Since characters from -128 to -1 are same as from +128 to +255, then what is the point of using unsigned char?

#include <stdio.h>
#include <conio.h>
int main()
{
    char a=-128;
    while(a<=-1)
    {
        printf("%c\n",a);
        a++;
    }
    getch();
    return 0;
}

The output of the above code is same as the output of the code below

#include <stdio.h>
#include <conio.h>
int main()
{
    unsigned char a=+128;
    while(a<=+254)
    {
        printf("%c\n",a);
        a++;
    }
    getch();
    return 0;
}

Then why we use unsigned char and signed char?

like image 319
Utkarsh Malviya Avatar asked Jan 07 '23 10:01

Utkarsh Malviya


2 Answers

K & R, chapter and verse, p. 43 and 44:

There is one subtle point about the conversion of characters to integers. The language does not specify whether variables of type char are signed or unsigned quantities. When a char is converted to an int, can it ever produce a negative integer? The answer varies from machine to machine, reflecting differences in architecture. On some machines, a char whose leftmost bit is 1 will be converted to a negative integer ("sign extension"). On others, a char is promoted to an int by adding zeros at the left end, and thus is always positive. [...] Arbitrary bit patterns stored in character variables may appear to be negative on some machines, yet positive on others. For portability, specify signed or unsigned if non-character data is to be stored in char variables.

like image 92
Rahul Tripathi Avatar answered Jan 09 '23 01:01

Rahul Tripathi


With printing characters - no difference:

The function printf() uses "%c" and takes the int argument and converts it to unsigned char and then prints it.

char a;
printf("%c\n",a);  // a is converted to int, then passed to printf()
unsigned char ua;
printf("%c\n",ua); // ua is converted to int, then passed to printf()

With printing values (numbers) - difference when system uses a char that is signed:

char a = -1;
printf("%d\n",a);     // --> -1
unsigned char ua = -1;
printf("%d\n",ua);    // --> 255  (Assume 8-bit unsigned char)

Note: Rare machines will have int the same size as char and other concerns apply.

So if code uses a as a number rather than a character, the printing differences are significant.

like image 29
chux - Reinstate Monica Avatar answered Jan 09 '23 00:01

chux - Reinstate Monica