gpt4 book ai didi

c - 为什么可以将自动值初始化为陷阱表示而不会导致UB?

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:30 25 4
gpt4 key购买 nike

在 6.2.6.1 p5 中,C11 说:

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. If such a representation is produced by a side effect that modifies all or any part of the object by an lvalue expression that does not have character type, the behavior is undefined.50) Such a representation is called a trap representation.

第 50 个脚注是:

Thus, an automatic variable can be initialized to a trap representation without causing undefined behavior, but the value of the variable cannot be used until a proper value is stored in it.

其实这两个我都听不懂

最佳答案

作为示例的最简单类型可能具有陷阱表示是 _Bool。事实上,只有 _Bool 的值为 01 时,它才被明确定义。所有其他值都是(或可以被视为)陷阱表示。

现在看看类似的东西

struct both {
_Bool b;
char c;
};

both two = { .c = 'a', };

printf("char: %c\n", two.c); // All fine
printf("bool: %s\n", two.b ? "true" : "false"); // error

所以 two.b 有一个陷阱值,只有当您尝试使用该值时您的程序才会出错,然后行为不再定义。例如,您的编译器可以决定通过等同于

的方式来实现对两个字符串的选择
(char const*[]){ "false", "true" }[two.b]

如果特定值不是 01,您的数组访问将越界。

关于c - 为什么可以将自动值初始化为陷阱表示而不会导致UB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33705073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com