Working with a Microchip 18f4620 PIC. This should be a standard ANSI C question, though.
Say I have
unsigned int16 badFlow=65535 //max unsigned int16 value
This has a binary value of 1111 1111 1111 1111.
if I then
badFlow++;
the bit pattern becomes 1 0000 0000 0000 0000
17 bits. Obviously badFlow == 0, but the additional flipped bit either
- gets discarded
- or resides at wherever
byte* flowPtr = &badFlow+2;
points.
I’m assuming the latter, but hoping for the former.
My problem: a coworker has written some bad code with a counter that has been overflowing on all produced products for ~2 years. Considering what our customers charge for use of these tools, that’s a few million dollars in peril due to potentially bad data.
Arithmetic in C takes place with values, not bytes in memory. Your expression
badFlow++is equivalent tobadFlow = badFlow + 1. The right-hand side is evaluated as typeint(due to default promotions, assumingintis larger than 16 bits; ifintis only 16 bits then it would be evaluated asunsigned int) resulting in 65536, then when 65536 is assigned into an unsigned 16-bit variable, it is reduced modulo 65536, resulting in 0.The important thing to get out of this answer is that
badFlow++is not a direct operation on the memory at&badFlow(although it could possibly be implemented as such on some implementations). It’s simply shorthand for an addition and assignment.