I've spent the past week doing a lot of embedded programming, and for me, this has mostly been handling having full-duplex communication between twenty devices on the same serial bus. It also means getting raw bytes and doing the memcpy(&myMessageStructVariable, buffer, sizeof(MessageStruct))
. Yes, that's not the best way, and certainly isn't how I'd build it if I didn't have full control over both ends of the network.
Of course, even with that, serial networks can have some noise and errors. That means sometimes I get a packet that isn't the right size, and memcpy
will happily read past the end of the buffer, because my const uint8_t * buffer
pointer is just a pointer, after all. It's on me to access memory safely. Errors result when I'm incautious.
Which brings us to Krzysztof`s submission. This code is deep inside of a device that's been on the market for twenty years, and has undergone many revisions, both hardware and software, over that time.
uint32_t tempHistVal1;
uint32_t tempHistVal2;
uint32_t tempHistVal3;
...
uint32_t tempHistVal20;
uint32_t get_avg_temp(){
uint32_t res=0;
uint32_t *ptr=&tempHistVal1;
for(uint32_t i=0;i<20;i++)
res+=ptr[i];
return res/20;
}
After the first few lines, you'll probably think to yourself, "that should probably be an array, shouldn't it?" Of course it should. The programmer who wrote this agrees with you.
The line uint32_t *ptr=&tempHistVal1
creates a pointer to the first variable. In C, the line between "pointer" and "array" is fuzzy, which means you can use the []
operator to "index" a pointer. So, the line res+=ptr[i]
grabs the i-th 32-bit integer after the ptr
s address.
Now it's likely that tempHistVal1
and tempHistVal2
are contiguous in memory. It's the most obvious way for the compiler to handle those variables. But there's no guarantee that's the case. The C specification guarantees that arrays represent contiguous blocks of memory, but not variables.
Krzysztof suggested that they change this to an array, but was shot down. "We don't change code that works!", management said. Krzysztof is left to prayto the gods of compilers and hardware platforms and memory alignment that these variables keep getting compiled in order, with no gaps.