简体   繁体   English

简单的C语法问题

[英]Simple C syntax Question

I ran into the following code in an old exam of the C course I'm taking: 我在参加的C课程的旧考试中遇到了以下代码:

struct QuestionSet{
    char q1:1;
    char q2:1;
    char q3:1;
}

I have no idea what the syntax "char q1:1" means, and I haven't been able to find it anywhere in "The C Programming Language" which is the course book. 我不知道语法“ char q1:1”是什么意思,并且在课程手册“ C编程语言”中的任何地方都找不到。 Can anyone explain? 谁能解释?

It's a bitfield . 这是位场 The number after the colon indicates the number of bits to assign to the struct element. 冒号后面的数字表示要分配给struct元素的位数。 So the three elements are all one bit wide, and are able to store two values: 0, and either 1 or -1 (depending on your compiler, though -1 would be the more logical option when considering two's-complement arithmetic). 因此,这三个元素都是一个位宽,并且能够存储两个值:0,以及1或-1(取决于您的编译器,尽管在考虑二进制补码算法时-1是更逻辑的选择)。

Bitfields are often used in microcontrollers programming, because it helps mapping registers in memory. 位域通常用于微控制器编程中,因为它有助于映射内存中的寄存器。 For example, for a 8 bits register, if each bit has a different meaning/usage, it is possible to represent the register value with a structure: 例如,对于一个8位寄存器,如果每个位具有不同的含义/用法,则可以用以下结构表示寄存器值:

struct exception_register
{
    bool enable_irq_0: 1;
    bool enable_irq_1: 1;
    bool enable_irq_2: 1;
    bool enable_irq_3: 1;
    bool irq_flag_0: 1;
    bool irq_flag_1: 1;
    bool irq_flag_2: 1;
    bool irq_flag_3: 1;
};

byte* the_register = 0x1234; // where 0x1234 is the address of the register in memory.

Then enabling exceptions 2 can be done like this: 然后可以这样启用异常2:

the_register->enable_irq_2 = true;

Which is more readable than: 比以下内容更具可读性:

*the_register |= (1 << 2);

This is not intended to answer the question, but may help to understand why bitfields can be usefull. 这并不是要回答这个问题,而是可以帮助您理解为什么位字段可以有用。

It seems to be a bitfield. 似乎是个位场。 Example Bitfield 示例位域

Bitfield may be useful on small memory. 位域在较小的内存上可能很有用。

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

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