Please take a look at this code:
#include <stdio.h>
#include <stdint.h>
int main()
{
uint8_t run = 1;
/* Define variable of interest and set to random value */
uint32_t dwTime = 0xdeadc0de;
/* Define uint16_t pointer */
uint16_t* tmpU16;
/* Assign least 16 bits from dwTime to tmpU16 by downcasting from uint32_t to uint16_t */
tmpU16 = (uint16_t*)&dwTime;
/* Print content of tmpU16 */
fprintf(stderr, "TEST: %04x\n", *tmpU16); /* Will print "TEST: c0de" here */
/* This loop will run exactly once */
while (run)
{
/* Print content of tmpU16 AGAIN (content of tmpU16 should not have changed here!) */
/* Will print "TEST: 0000" here when optimization is enabled */
/* Will print "TEST: c0de" here when optimization is disabled */
fprintf(stderr, "TEST: %04x\n", *tmpU16);
/* Increment tmpU16 pointer by 1 (yes, this does not make sense but it should not do any harm
either, unless something gets written to its address AFTER incrementing */
tmpU16++;
run--;
}
return 0;
}
When compiling this code with GCC 11 and optimization enabled (for example -O2) it will produce following output:
TEST: c0de
TEST: 0000
When this code is compiled without optimization (-O0) it will produce:
TEST: c0de
TEST: c0de
I assumed after the first fprintf is executed, the next fprintf inside the while loop will be executed immediately. In between these two fprintfs nothing should happen, hence content of tmpU16 stay unchanged.
However, when I comment out the tmpU16++ pointer incrementation, it produces correct output with optimization.
Why is this, what's happening here?