3 ms·
I agree with everything in the article - the example of non-intuitive effects of the strict aliasing rule, a tricky integer overflow example, and the unpopular
by nayuki 8y ago
I agree with everything in the article - the example of non-intuitive effects of the strict aliasing rule, a tricky integer overflow example, and the unpopular plea to switch away from C/C++.
When I write C and C++ code, I try to make my logic portable and standards-compliant so that it will work on all platforms. So instead of assuming int is 32 bits, I am only allowed to assume that int is at least 16 bits wide. I assume that sizeof(char) could equal sizeof(int) and both could be 64 bits. I avoid bitwise manipulation on negative numbers, because they're not guaranteed to be two's complement. Keeping all of these pessimistic assumptions in mind while I code is a mental burden that I don't experience in other languages.
Regarding integer promotions, here is one tricky situation I reasoned about and asked in https://stackoverflow.com/questions/39964651/is-masking-before-unsigned-left-shift-in-c-c-too-paranoid https://stackoverflow.com/questions/39964651/is-masking-befo... . Suppose you want to compute:
uint32_t a = UINT32_C(0xFFFFFFFF);
uint32_t b = a << 31;
b should be 0x80000000
Looks innocent, eh? Left-shifting an unsigned integer will discard the top bits and never cause undefined behavior. Except, this reasoning can be wrong on some platforms. Suppose:
typedef unsigned short uint32_t;
typedef int int48_t;
Now (uint32_t)a → (unsigned short)a → (int)a → (int48_t)a, due to typedefs and integer promotion. But because a is a signed integer, it is undefined behavior to shift 1's into the sign bit. Kaboom.
- jjnoakes 8y agoI wonder if a future c standard can fix this in some way. Say by promoting unsigned types to unsigned int instead of int...
- garaetjjte 8y ago>I avoid bitwise manipulation on negative numbers, because they're not guaranteed to be two's complement. This seems purely theoretical, as there is no reasonable architectures that are not using two's complement. It will be defined as two's complement in C++20. (but still with signed overflow UB, to keep some optimizations possible)
- baby 8y agoI try to never use int personally, if uint8_t et al. exist, it's for a reason.