Hey guys,
I’ve been struggling to find accurate, complete and reliable information on this topic. At best, I’ve gotten partial truths, but mostly, conflicting advice. My go-to for answers, the complang.c.faq compilation in pdf form, surprisingly doesn’t have anything on this, perhaps an indicator of how little understood the topic is; while The Standard is simultaneously a little too vague and rather too broad in the matter.
This is what I understand as true:
Unsigned integers never overflow. Their wrap around behavior is well specified and defined.
Signed integers can overflow. Depending on the conditions, the overflow can invoke implementation defined or unspecified behavior.
When does overflow occur?
*When performing arithmetic operations in which both left and right operands are signed integers -either by nature or promotion- and the result is bigger than the maximum representable value for their size.
-[+, -, *, /, %, ++, –, <<] and their compound assignment counterparts can overflow.
-Comparison, bitwise and boolean expressions and their compound assignement counterparts will not result in overflow.
But what about these cases.
*Right shifting a signed integer.
*Right shifting using a negative value as the right hand operand.
*Assigning a signed int of bigger precision to a lower precision int and assigning an unsigned int greater than INT_MAX to a signed int. In my experience these result in truncation, but is this the “implementation defined” result of an overflow. Or is this specified behavior?
*The same with casting. I though for a long time that casting an unsigned int to a signed int of the same precision would be a mere reinterpretation of the same underlying bit pattern -at least on a two’s complement machine- and thus completely valid. I’ve faithfully relied on this to do things like: (int32_t)(uint32_t)(int64_t) But after reading conflicting reports, I’m not sure if I’ve been relying on implementation defined behavior and my code might break with the next gcc version.
*Trap values.
If you’re confident in your knowledge, I will be eternally grateful if you could shed some light in the matter, or point me to a good source of information.
Thank you.