4 ms·
>If you find yourself typing char [..] into new code, you're doing it wrong. >The only acceptable use of char in 2016 is if a pre-existing API requires char (e
by jhallenworld 11y ago
>If you find yourself typing char [..] into new code, you're doing it wrong.
>The only acceptable use of char in 2016 is if a pre-existing API requires char (e.g. strncat, printf'ing "%s", ...) or if you're initializing a read-only string (e.g. const char hello = "hello";) because the C type of string literals ("hello") is char .
Heh, basically you need to use 'char ' for strings. I would far prefer if strings were unsigned so that I could use 'uint8_t ', but if you try it you'll get tons of conversion warnings and your code will look weird.
- bluetomcat 11y agoThe other widespread use of char pointers is when you need to perform pointer arithmetic over a buffer (without any dereferencing) in steps of 1 (as sizeof(char) == 1). Void pointers do not allow pointer arithmetic (GCC allows it as an extension).
- gvb 11y agoHe covers that in the next section "Signedness" and more thoroughly in "System-Dependent Types" where he recommands (properly) using uintptr_t and intptr_t: The correct type for pointer math is uintptr_t defined in <stddef.h>.
- bluetomcat 11y agoCorrect me if I'm wrong, but in my understanding, the primary purpose of uintptr_t is to type-pun a pointer into a compatible integer, inspect/modify the bits of the integer and then cast it back to a pointer of the same type. I don't feel like it's the right type for simple pointer arithmetic.
- _kst_ 11y agoYou're right, using uintptr_t for pointer arithmetic is a bad idea. I've worked on systems (Cray vector machines) where converting a pointer to an integer type, performing arithmetic on the integer, and converting back to a pointer could yield meaningless results. (Hardware addresses were 64-bit addresses of 64-bit words; byte pointers were implemented by storing a 3-bit offset in the high-order bits of the pointer.) Pointer arithmetic works. It causes undefined behavior if it goes outside the address range of the enclosing object, but in those cases converting to uintptr_t and performing arithmetic will give you garbage results anyway.
- _kst_ 11y agoIf you want to access a buffer as raw bytes (which may or may not be octets), use `unsigned char`. Plain `char` may be either signed or unsigned, depending on the implementation.