在下面的代码中
#include <iostream>
using namespace std;
struct field
{
unsigned first : 5;
unsigned second : 9;
};
int main()
{
union
{
field word;
int i;
};
i = 0;
cout<<"First is : "<<word.first<<" Second is : "<<word.second<<" I is "<<i<<"\n";
word.first = 2;
cout<<"First is : "<<word.first<<" Second is : "<<word.second<<" I is "<<i<<"\n";
return 0;
}
当我初始化 word.first = 2 时,正如预期的那样,它会更新单词的 5 位,并给出所需的输出。'i' 的输出有点令人困惑。当 word.first = 2 时,i 给出的输出为 2,当我执行 word.second = 2 时,i 的输出为 64。由于它们共享相同的内存块,后一种情况下的输出(对于 i)不应该是2?