【发布时间】:2014-08-14 13:05:08
【问题描述】:
考虑以下代码。没问题还是会导致未定义的行为?
#include <iostream>
int main()
{
{
unsigned char binary[] = {0, 5, 10};
bool* x = reinterpret_cast<bool*>(&binary[0]);
for (unsigned int i = 0; i < 3; ++i)
{
std::cout << (x[i] ? 1 : 0) << " ";
}
}
{
unsigned char b = 255;
bool* x = reinterpret_cast<bool*>(&b);
std::cout << (*x ? 1 : 0) << std::endl;
}
return 0;
}
使用 gcc 4.6 到 4.8 编译时的输出是
0 5 10 1
但仅限于优化(-O1 等)。
Clang 结果
0 1 1 1
即使有优化。
现在如果将y[i] ? 1 : 0 更改为y[i] ? 2 : 1 gcc 结果是
1 2 2 1.
有什么想法,或者只是因为演员阵容而导致的未定义行为?
【问题讨论】:
-
部分问题可以改写为:标准是否保证
bool和char具有相同的大小和对齐方式...我相信是的,但我不确定。