结构变量不会因赋值而改变 [英] Struct variable doesn't changed by assignment

查看:33
本文介绍了结构变量不会因赋值而改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct st  
{  
    int a1 : 3;  
    int a2 : 2;  
    int a3 : 1;  
}

void main(void)
{
    x.a3 = -1;  

    if (x.a3 == -1) printf("TRUE\n");
    else printf("FALSE\n");

    x.a3 = 1;  
    if (x.a3 == 1) printf("TRUE\n");
    else printf("FALSE\n");  
}

如果 'x.a3 = -1;' 首先如果 TRUE.
但是,为什么 'x.a3 = 1' 在第二个 if 没有改变?它仍然是 x.a3 = -1.

In case, 'x.a3 = -1;' First if is TRUE.
But, why 'x.a3 = 1' doesn't changed in second if ? It's still x.a3 = -1.

还有
如果我首先输入 'x.a3 = 1;' ,它仍然是 x.a3 == 1 !!没变!

And
If I type 'x.a3 = 1;' in first if, it still x.a3 = = 1 !! It doesn't changed!

XCode 调试结果

推荐答案

问题是,一个带符号的 1 位变量只能容纳两个值,-10(阅读Two 的补码).仅保存 1(准确地说是 +1)的值是不够的.

The problem is, a signed 1 bit variable can hold only two values, -1 and 0 (Read about Two's complement). It is not sufficient to hold a value of 1 (+1, to be exact).

详细说明,一边写作业

 x.a3 = 1;

整数常量1的值存储在为成员a3保留的内存位置,但在访问变量时,根据变量的符号(也许signedunsigned,实现定义的行为,按照章节 §6.7.2/P5),表示将从内存中读取.

the value of integer constant 1 is stored into the memory location reserved for the member a3, but while accessing the variable, as per the signedness of the variable (maybe signed or unsigned, implementation defined behaviour, as per chapter §6.7.2/P5), the representation will be read from the memory.

1stored 值在二进制补码中的表示,将产生结果 -1(根据 MSB 值),所以== 1 的条件检查总是会失败.

The representation of a stored value of 1 in two's complement, will produce the result -1 (as per MSB value), so a condition check with == 1 will fail, always.

这篇关于结构变量不会因赋值而改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆