次のコードstd::cout
では、値を出力しませんが、出力printf
します。どうしてこれなの?
#include <iostream>
#include <cstdio>
struct bits
{
union
{
unsigned char b;
struct
{
unsigned char b0:1, b1:1, b2:1, b3:1, b4:1, b5:1, b6:1, b7:1;
};
};
};
const union
{
bits b[3];
char c[3];
} CU = { .c = { -1, 0, 1 }};
int main()
{
std::cout << "----- chars:\n";
std::cout << "\tstd::cout (c): " << CU.c[0]
<< ", " << CU.c[1]
<< ", " << CU.c[2]
<< "\n";
printf("\tprintf (c): %d, %d, %d\n", CU.c[0],
CU.c[1],
CU.c[2]);
std::cout << "\n----- bits:\n";
for (int i=0;i<3;i++)
{
std::cout << "\tstd::cout\n\t\t(bits): [" << i << "] = "
<< CU.b[i].b0 << CU.b[i].b1 << CU.b[i].b2
<< CU.b[i].b3 << CU.b[i].b4 << CU.b[i].b5
<< CU.b[i].b6 << CU.b[i].b7 << "\n";
std::cout << "\t\t(b): [" << i << "] = " << CU.b[i].b << "\n";
printf("\tprintf\n\t\t(bits): [%d] = %d%d%d%d%d%d%d%d\n",
i, CU.b[i].b0, CU.b[i].b1, CU.b[i].b2,
CU.b[i].b3, CU.b[i].b4, CU.b[i].b5,
CU.b[i].b6, CU.b[i].b7);
printf("\t\t(b): [%d] = %d\n\n", i, CU.b[i].b);
}
return 0;
}
出力:
----- chars:
std::cout (c): �, ,
printf (c): -1, 0, 1
----- bits:
std::cout
(bits): [0] =
(b): [0] = �
printf
(bits): [0] = 11111111
(b): [0] = 255
std::cout
(bits): [1] =
(b): [1] =
printf
(bits): [1] = 00000000
(b): [1] = 0
std::cout
(bits): [2] =
(b): [2] =
printf
(bits): [2] = 10000000
(b): [2] = 1