5 ms·
This confirms one of the guidelines I've always been taught; char is not an arithmetic type, and never treat it as such. It represents ascii characters, and not
by flqn 7y ago
This confirms one of the guidelines I've always been taught; char is not an arithmetic type, and never treat it as such. It represents ascii characters, and nothing else.
- Piezoid 7y ago(u)int8_t have the same problems, including aliasing because they are just alias of (unsigned) char. Sometimes it's nice to have modular arithmetic mod 256, or compact memory layout for eg. count sketches.
- wahern 7y agoIf int8_t exists[1], then you know that char is 8 bits[2] and therefore know that char in char + char always promotes to int because int must have at least 16 value bits and a 16-bit int can represent any char value regardless of signedness. [1] int8_t is not required. [2] char is the fundamental unit of addressability. sizeof char always evaluates to 1, sizeof int8_t must be non-0, char must be at least 8 bits, and int8_t must be precisely 8 bits, therefore sizeof int8_t == sizeof char and CHAR_BIT == 8.
- SamReidHughes 7y ago'0' through '9' are guaranteed to be contiguous, so doing arithmetic around that fact is legitimate. And char does not generally represent ASCII characters; it could be some other charset.
- _kst_ 7y agoI disagree, mostly. char is an arithmetic type, but it rarely makes sense to treat it as one, because its signedness is implementation-defined. If you want a very narrow integer type, both signed char and unsigned char are arithmetic types, and can reasonably be used that way. (Arrays of unsigned char are also used for raw memory.) And you should understand how char, signed char, and unsigned char behave when you do use them as arithmetic types. Promotion to int or unsigned int, depending on the range of the type, can be confusing. The same applies to all integer types with lower rank than int, including short, unsigned short, and intN_t and uintN_t for N==8 (and probably for N==16, and maybe for larger N). Note also that this: char c = '0'; ++c; is guaranteed to set c to '1'. (This guarantee applies only to decimal digits, not to letters.)
- kccqzy 7y agoThe compiler doesn't agree with you. #include <type_traits> static_assert(std::is_arithmetic<char>::value, "char is arithmetic");
- beached_whale 7y agoI would use this for anything < int/unsigned. a short * short can result in a signed integer overflow and that is UB.