c++中无符号字符b[2]的初始值是多少

what is the initial value of unsigned char b[2] in c++?

本文关键字:多少 无符号 字符 c++      更新时间:2023-10-16
// unions.cpp
// Defines and uses a union.
// ---------------------------------------------------
#include <iostream>
using namespace std;
union WordByte
{
private:
unsigned short w;
unsigned char b[2];                         // an array member of size 2? 
public:
unsigned short& word()     { return w; }    // public methods have access to the private members
unsigned char& lowByte() { return b[0]; }
unsigned char& highByte(){ return b[1]; }
};

int main()
{
WordByte wb;                                   // create an instance of WordByte with name wb
wb.word() = 256;                               // access the public members .word()
cout << "nWord:" << (int)wb.word();           // access the public members .word(), transfer the returned value to int type
cout << "nLow-byte: " << (int)wb.lowByte()    // access the public members .lowByte(), explicit casting
<< "nHigh-byte: " << (int)wb.highByte()  // access the public members .highByte(), explicit casting
<< endl;
return 0;
}

嗨,以上代码不包括在《c++完整指南》一书中。当我运行它时,输出如下:

~$ g++ units.cpp
~$ ./a.out
Word:256
Low-byte: 0
High-byte: 1

我理解为什么输出256。但是为什么输出中有0和1?

在C++中,由于union当前没有活动成员,因此读取任何成员时的行为都是未定义的。

联合成员的类型不相关。(未初始化的自动unsigned char是可读的;这是读取未初始化变量未定义的一般规则的一个重要例外。(

(请注意,在C中,读回unsigned char数组成员的行为不会是未定义的——这是因为C允许并集类型双关;C++不允许。(

联合是一种数据类型,其中定义的所有元素都位于同一内存地址,并被分配实现其最大元素所需的内存。

在您的例子中,您有一个带有2个字符数组(也是16位(的并集中的无符号短(16位(。

碰巧的是,在处理器上,您正在使用无符号short的最高有效字节到最低有效字节的排列,使得其最高有效字节与b[1]位于同一内存位置,而其最低有效字节位于b[0]的内存位置。

有时,您会看到以这种方式错误地使用联合来快速将数据类型转换为字节数组,反之亦然,但要小心,因为它是否有效取决于处理器。