_布尔类型和严格的别名 [英] _Bool type and strict aliasing
问题描述
我试图编写一些宏以供类型安全使用_Bool
,然后对我的代码进行压力测试.出于邪恶测试的目的,我想出了这个肮脏的技巧:
I was trying to write some macros for type safe use of _Bool
and then stress test my code. For evil testing purposes, I came up with this dirty hack:
_Bool b=0;
*(unsigned char*)&b = 42;
鉴于_Bool
在实现sizeof(_Bool)==1
上为1个字节),我看不到这种黑客是如何违反C标准的.这不应该是严格的别名冲突.
Given that _Bool
is 1 byte on the implementation sizeof(_Bool)==1
), I don't see how this hack violates the C standard. It shouldn't be a strict aliasing violation.
但是通过各种编译器运行该程序时,我遇到了问题:
Yet when running this program through various compilers, I get problems:
#include <stdio.h>
int main(void)
{
_Static_assert(sizeof(_Bool)==1, "_Bool is not 1 byte");
_Bool b=0;
*(unsigned char*)&b = 42;
printf("%d ", b);
printf("%d", b!=0 );
return 0;
}
(代码依赖于printf
隐式默认参数提升为int
)
(The code relies on printf
implicit default argument promotion to int
)
某些版本的gcc和clang提供输出42 42
,其他版本提供0 0
.即使禁用优化.我本来期望42 1
.
Some versions of gcc and clang give output 42 42
, others give 0 0
. Even with optimizations disabled. I would have expected 42 1
.
似乎编译器假定_Bool
只能是1
或0
,但同时在第一种情况下它愉快地打印42
.
It would seem that the compilers assume that _Bool
can only be 1
or 0
, yet at the same time it happily prints 42
in the first case.
Q1:为什么?上面的代码是否包含未定义的行为?
Q1: Why is this? Does the above code contain undefined behavior?
Q2:sizeof(_Bool)
的可靠性如何? C17 6.5.3.4完全没有提到_Bool
.
Q2: How reliable is sizeof(_Bool)
? C17 6.5.3.4 does not mention _Bool
at all.
推荐答案
Q1:为什么?上面的代码是否包含未定义的行为?
Q1: Why is this? Does the above code contain undefined behavior?
是的,确实如此.存储有效,但随后读取为_Bool
无效.
Yes, it does. The store is valid, but subsequently reading that as a _Bool
is not.
6.2.6类型的表示形式
6.2.6.1常规
5某些对象表示形式不必表示对象类型的值.如果对象的存储值具有这种表示形式,并且由不具有字符类型的左值表达式读取,则该行为是不确定的. [...]
5 Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. [...]
Q2:
sizeof(_Bool)
的可靠性如何? C17 6.5.3.4完全没有提到_Bool
.
Q2: How reliable is
sizeof(_Bool)
? C17 6.5.3.4 does not mention_Bool
at all.
它将可靠地告诉您存储一个_Bool
所需的字节数. 6.5.3.4也没有提到int
,但是您不是在问sizeof(int)
是否可靠,对吗?
It will reliably tell you the number of bytes that are needed to store one _Bool
. 6.5.3.4 also doesn't mention int
, but you're not asking whether sizeof(int)
is reliable, are you?
这篇关于_布尔类型和严格的别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!