[英]struct default values in c
I came across this problem in C using structs.I'm not sure of what is really happening here Thanks 我在C中使用structs遇到了这个问题。我不确定这里到底发生了什么
#include<stdio.h>
int main()
{
struct num1
{
int n1:2;
int n2:3;
int n3:4;
};
struct num1 num={3,4,5};
printf("%d %d %d\n",num.n1,num.n2,num.n3);
return 0;
}
The obtained output is 获得的输出是
-1 -4 5
-1 -4 5
These are bit fields, the number after the :
specifies how many bits are in that member. 这些是位字段,“
:
后面的数字指定该成员中有多少位。
int n1:2
means a signed integer with 2 bits. 表示2位有符号整数。 In two's complement notation, this allows for values from
-2
to 1
; 用二进制补码表示,这允许从
-2
到1
值; in sign+magnitude notation it allows for -1
to 1
. 在符号+幅度符号中,它允许
-1
到1
。 When you try to assign 3
to this member, you get overflow, which results in undefined behavior. 尝试将
3
分配给该成员时,您会溢出,从而导致未定义的行为。
Similarly 相似地
int n2:3
means a signied integer with 3 bits, whose range is -4
to 3
in two's complement, -3
to 3
in sign+magnitude, so assigning 4
causes overflow. 是指具有3个比特,其范围是一个整数signied
-4
到3
在二的补码, -3
至3
中的符号+大小,所以分配4
原因溢出。
int n3:4
has a range from -8
to 7
or -7
to 7
, so assigning 5 fits into it, so there's no overflow. 的范围是
-8
到7
或-7
到7
,因此将5分配给它,因此没有溢出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.