c++中无符号字符b[2]的初始值是多少
what is the initial value of unsigned char b[2] in c++?
// 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]的内存位置。
有时,您会看到以这种方式错误地使用联合来快速将数据类型转换为字节数组,反之亦然,但要小心,因为它是否有效取决于处理器。
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将无符号char*转换为std::istream*C++
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存
- 如何打印boost多精度128位无符号整数
- C++模板函数,用于比较任何无符号整数和有符号整数
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 获取隐式转换溢出从无符号到已签名的警告
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 从 std::vector<无符号字符>切片中提取 int?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- C4018:类内有符号、无符号不匹配
- c++中无符号字符b[2]的初始值是多少
- 无符号长长的确切大小应该是多少