在 C 中获取临时(复合文字)参数的地址

2024-05-08

I can't imagine this isn't already duplicate, but I can't easily find the answer since the more complex scenarios specifically to C++ seem to dominate the discussion0.

在 C99 中获取函数调用的参数列表中构造的临时地址是否合法?

例如,类似的东西init_list or init_desig_init如下:

typedef struct {
  int x;
  int y;
} point_t;

int manhattan(point_t *p) {
  return p->x + p->y;
}

int init_list() {
  return manhattan(&(point_t){1, 2});
}

int init_desig_init() {
  return manhattan(&(point_t){.x = 1});
}

The big three1 seem to compile it OK https://godbolt.org/g/RpD9S3, but I couldn't actually find a reference explaining that the lifetime of the temporary will be extended at least through the function call.


0 As it turns out, based on the answer by M.M below, part of my searching issues was because I was looking for information on temporaries, while the correct C term for this particular initialization construct is compound literal.

1 I should call it "the big cross-platform three" really, in deference to MSVC, but actually I really just mean "the C compilers godbolt supports".


(point_t){1, 2}不是“临时”。它是一个复合文字。 (C++ 中相同的标记序列具有不同的含义,这两种语言不应相互混淆)。

复合文字是左值,因此使用一元是合法的&其上的操作员。 C11 6.5.2.5/5 涵盖了存储期限:

如果复合文字出现在函数体之外,则对象 具有静态存储期限;否则,它具有与封闭块关联的自动存储持续时间。

所以这段代码是正确的,并且复合文字一直存在,直到声明它的函数结束为止。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C 中获取临时(复合文字)参数的地址 的相关文章

随机推荐