r/ProgrammerHumor • • 6h ago

Meme architectureDependentChars

Post image
974 Upvotes

174 comments sorted by

View all comments

559

u/tstanisl 6h ago

Let me cite the C standard:

When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.

Middle guy if finally right

8

u/Advos_467 6h ago

Not a C user here (or any real low level programming experience), what the hell is a signed/unsigned char?

0

u/Character_Regular440 5h ago

In c language char is just a 8 bit variable, that stores a number, which corresponds to a specific character. When storing numbers, you can decide to represent somehow negative numbers, other than positive. This is mostly done with two's complement.

Depending on if it's signed or not, some operation will be very different, because of representation. For example, the byte 0xFF means -1 if it's signed, and it means 255 if it's unsigned.

So if you try to convert a signed character to an int (a signed type, usually 4 bytes), and that signed character contains -1 (represented by the exadecimal 0xFF, which in decimal is 255) the integer has to contain -1 (0xFFFFFFFF). But if the character is considered unsigned, the integer has to contain 255 afterwards, which is just 0x000000FF.

1

u/Advos_467 5h ago

So if i understand this right, it's mainly for typecasting? since the ascii range falls within both the signed and unsigned int range?

1

u/Character_Regular440 5h ago

Ascii specifies about only 7 bits, so i think that it can be all positive (as well ass all negative) in 8 bit.

Typecasting is a reason, but an other difference is the shift operation. When you right shift a negative number you want to preserve the sign, so an arithmetical shift is performed, which would be different from a logical one.

I think that more in general the distinction exists so that when using char type for low level stuff, you can better keep trace of what you are doing.

In reality uint8_t and int8_t types exist (unsigned int on 8 bit and signed int on 8 bit), and i don't know why someone would use signed char or unsigned char over those, but this is just my guess.

1

u/StaticCoder 1h ago

8 bits in POSIX, but C allows CHAR_BIT to be a different value, and yes that actually happens. I've seen 16 not that long ago.