请查看以下代码:
#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;
}
当使用GCC 11编译此代码并启用优化(例如-O2
)时,它将产生以下输出:
TEST: c0de
TEST: 0000
当编译此代码时,没有进行优化(-O0
),它将生成:
TEST: c0de
TEST: c0de
我假设在执行第一个fprintf
之后,while循环中的下一个fprintf
将立即执行.在这两个fprintf
之间什么都不应该发生,因此tmpU16
的内容保持不变.
然而,当我注释掉tmpU16++
指针增量时,它会产生正确的优化输出.
为什么,这里发生了什么?