简体   繁体   English

将uint32变量转换为位字段 - 未定义的行为?

[英]Cast a uint32 variable to a bit field - undefined behavior?

I have a register definition provided by the microcontroller manufacturer that can be handled as a bit field. 我有一个由微控制器制造商提供的寄存器定义,可以作为位字段处理。 The register is defined as follows: 寄存器定义如下:

#define SCU_WDTSCON0 (*( SCU_WDTSCON0_type *) 0xf00360f0u)

The bit field definition looks like this: 位字段定义如下所示:

typedef volatile union {
unsigned U;
int I;
struct {
    unsigned    ENDINIT  :1;    // [0:0] End-of-Initialization Control Bit
    unsigned    LCK  :1;    // [1:1] Lock Bit to Control Access to WDTxCON0
    unsigned    HPW0     :2;    // [3:2] Hardware Password 0
    unsigned    HPW1     :4;    // [7:4] Hardware Password 1
    unsigned    PW   :8;    // [15:8] User-Definable Password Field for Access to WDTxCON0
    unsigned    REL  :16;   // [31:16] Reload Value for the WDT
  } B;
} SCU_WDTSCON0_type;

Instead of directly writing to the register, I want to use a uint32 buffer variable first, but still be able to edit it in the manner of the register bit field definition. 我想先使用uint32缓冲区变量,而不是直接写入寄存器,但仍然能够以寄存器位字段定义的方式对其进行编辑。 This implementation seems to be working, as the address is just replaced with &buffer_variable: 这个实现似乎有效,因为地址只是替换为&buffer_variable:

volatile uint32 buffer_variable;
SCU_WDTSCON0_type register_buffer = (*( SCU_WDTSCON0_type *) &buffer_variable);

Could this lead to undefined behavior? 这会导致未定义的行为吗?

Your buffer variable needs to be exactly the same type as one of the union members, in this case unsigned . 您的缓冲区变量需要与其中一个联合成员完全相同,在本例中为unsigned In case the compiler treats uint32 and unsigned as different types, it will lead to undefined behavior (violates strict aliasing rule). 如果编译器将uint32unsigned视为不同类型,则会导致未定义的行为(违反严格的别名规则)。 Otherwise, if they are the same type, the code is fine. 否则,如果它们是相同的类型,代码就可以了。

(As a side note, most bugs related to strict aliasing violations are caused by the compiler's optimizer. In case of volatile variables, this is less of an issue, since the compiler isn't allowed to optimize them anyway. So in practice, I doubt you'll ever encounter any UB for this scenario, even though it could be UB in theory.) (作为旁注,大多数与严格别名违规相关的错误都是由编译器的优化器引起的。对于volatile变量,这不是问题,因为编译器无论如何都不允许优化它们。所以在实践中,我怀疑你在这种情况下会遇到任何UB,即使理论上它可能是UB。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM