gpt4 book ai didi

c - 在 C 语言中,是否可以在语义上创建类型不完整的左值?

转载 作者:太空狗 更新时间:2023-10-29 16:44:46 26 4
gpt4 key购买 nike

在C89标准中,我找到了以下部分:

3.2.2.1 Lvalues and function designators

Except when it is the operand of the sizeof operator, the unary & operator, the ++ operator, the -- operator, or the left operand of the . operator or an assignment operator, an lvalue that does not have array type is converted to the value stored in the designated object (and is no longer an lvalue). If the lvalue has qualified type, the value has the unqualified version of the type of the lvalue; otherwise the value has the type of the lvalue. If the lvalue has an incomplete type and does not have array type, the behavior is undefined.

如果我没看错的话,它允许我们创建一个 lvalue 并在其上应用一些运算符,这会编译并可能在运行时导致未定义的行为。

问题是,我想不出一个可以通过编译器语义检查并触发未定义行为的“类型不完整的左值”的例子。

考虑一个左值是

An lvalue is an expression (with an object type or an incomplete type other than void) that designates an object.

那个不完整的类型是

Types are partitioned into object types (types that describe objects), function types (types that describe functions), and incomplete types (types that describe objects but lack information needed to determine their sizes).

我试过的一个失败的程序:

struct i_am_incomplete;
int main(void)
{
struct i_am_incomplete *p;
*(p + 1);
return 0;
}

出现以下错误:

error: arithmetic on a pointer to an incomplete type 'struct i_am_incomplete'
*(p + 1);
~ ^

任何人都可以想出一个例子吗?可以通过编译器语义检查并触发未定义行为的“类型不完整的左值”示例。


更新:

正如@algrid 在回答中所说,我误解了 undefined behavior,其中包含 compile error 作为选项。

也许我在 split 头发,我仍然想知道这里的潜在动机是更喜欢 undefined behavior 而不是 disallowing an lvalue to have an incomplete type

最佳答案

我相信这个程序证明了这一点:

struct S;
struct S *s, *f();

int main(void)
{
s = f();
if ( 0 )
*s; // here
}

struct S { int x; };
struct S *f() { static struct S y; return &y; }

在标记的行中,*s 是一个不完整类型的左值,它不属于您引用的 3.2.2.1 中的任何“Except...”情况(这是现行标准中的 6.3.2.1/2)。因此这是未定义的行为。

我在 gcc 和 clang 中尝试了我的程序,但它们都拒绝了它,错误是无法取消引用指向不完整类型的指针;但是我在标准中找不到任何违反约束的地方,所以我相信编译器拒绝该程序是不正确的。或者标准可能因省略此类约束而存在缺陷,这是有道理的。

(由于代码在 if(0) 中,这意味着编译器不能仅仅因为它是未定义的行为而拒绝它)。

关于c - 在 C 语言中,是否可以在语义上创建类型不完整的左值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46029394/

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