简单的C语法问题
我在我正在参加的 C 课程的旧考试中遇到了以下代码:
struct QuestionSet{
char q1:1;
char q2:1;
char q3:1;
}
我不知道语法“char q1:1”的含义,并且我无法在“C 编程”中的任何地方找到它语言”,这是课本。谁能解释一下吗?
I ran into the following code in an old exam of the C course I'm taking:
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. Can anyone explain?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个位字段。冒号后面的数字表示分配给结构元素的位数。因此,这三个元素都是一位宽,并且能够存储两个值:0、1 或 -1(取决于您的编译器,尽管在考虑二进制补码算术时,-1 是更合乎逻辑的选项)。
It's a bitfield. The number after the colon indicates the number of bits to assign to the struct element. 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).
位域经常用于微控制器编程,因为它有助于映射内存中的寄存器。例如,对于 8 位寄存器,如果每个位都有不同的含义/用途,则可以用结构来表示寄存器值:
然后启用异常 2 可以这样完成:
哪个比以下更具可读性:
这不是旨在回答这个问题,但可能有助于理解为什么位字段有用。
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:
Then enabling exceptions 2 can be done like this:
Which is more readable than:
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.