|
|
Log in / Subscribe / Register

Would you like signs with those chars?

Would you like signs with those chars?

Posted Oct 25, 2022 5:09 UTC (Tue) by SLi (subscriber, #53131)
In reply to: Would you like signs with those chars? by NYKevin
Parent article: Would you like signs with those chars?

I really wonder (but am too lazy to Google now) what even is the history of signed chars. It seemed like a weird thing to me anyway. Was it some kind of wish to have a type that represents "all the characters we care about" and -1 for EOF, in times before the relevant routines were int?


to post comments

Would you like signs with those chars?

Posted Oct 25, 2022 16:15 UTC (Tue) by khim (subscriber, #9252) [Link]

I suspect it was just added when the C Standard committee realized that on some platforms simple char is unsigned. They needed single-byte signed type thus signed char was born.

Would you like signs with those chars?

Posted Oct 27, 2022 2:09 UTC (Thu) by gdt (subscriber, #6284) [Link] (2 responses)

The problem being solved is moving a byte in memory to a word-sized register. If you want to do that load in one processor instruction then you have to accept the processor's choice of sign extension or otherwise as that byte is expanded into the register.

If the language insists on "char" being "unsigned char" then some processors will need to follow the register load with an AND instruction to clear the sign extension. If loading that register also sets register flags (eg, Negative) then you'll need to clear those register flags too. You could, of course, perhaps avoid this with careful compiler optimisations, but that's asking too much of the compilers of the era.

Well before the ANSI standards committee started work, the convention in C was to let these differences in processor implementations shine through, with an obligation on people writing code intended to be 'portable' between differing processors to deal with the results. Considering that C was a systems programming language, this wasn't an unreasonable choice.

Would you like signs with those chars?

Posted Oct 27, 2022 6:01 UTC (Thu) by SLi (subscriber, #53131) [Link]

Ah, right, makes total sense. Thank you!

Would you like signs with those chars?

Posted Oct 27, 2022 7:18 UTC (Thu) by joib (subscriber, #8541) [Link]

https://trofi.github.io/posts/203-signed-char-or-unsigned... has some investigation on this issue. Turns out there are quite a few architectures that only provide zero extending byte loads but the ABI has chosen char's to be signed, thus requiring an extra instruction to patch it up.

(That blog post is a few years old and doesn't include results for RISC-V, but I understand that RISC-V is like ARM, in that it provides both zero extending and sign extending byte loads but the ABI has chosen char's to be unsigned)


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds