在C中获取临时(复合文字)参数的地址 [英] Taking address of temporary (compound literal) parameter in C

查看:109
本文介绍了在C中获取临时(复合文字)参数的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法想象这还不是重复的,但是我无法轻易找到答案,因为专门针对C ++的更复杂的场景似乎在讨论中占主导地位. 0 .

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中的函数调用的参数列表中构造的临时地址是否合法?

Is it legal to take take the address of a temporary constructed in the parameter list of a function call in C99?

例如,如下所示的init_listinit_desig_init之类的东西:

For example, something like init_list or init_desig_init as follows:

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});
}

三巨头 1 似乎可以编译它,但是我实际找不到参考资料来解释该临时文件的生存期至少会通过该函数调用来延长.

The big three1 seem to compile it OK, 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 事实证明,根据下面 MM 的回答,我搜索的部分问题是因为我正在寻找有关临时雇员的信息,而针对此特定初始化构造的正确C术语是复合文字.

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 确实,与MSVC相比,我应该称其为大跨平台三者",但实际上我只是说"C编译器Godbolt支持".

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 ++中相同的令牌序列具有不同的含义,这两种语言不应相互混淆.)

(point_t){1, 2} is not a "temporary". It is a compound literal. (The same sequence of tokens in C++ has a different meaning, these two languages should not be confused with each other).

复合文字是左值,因此在其上使用一元&运算符是合法的. C11 6.5.2.5/5涵盖了存储期限:

A compound literal is an lvalue, so it is legal to use the unary & operator on it. The storage duration is covered by C11 6.5.2.5/5:

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

If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

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

So this code is correct, and the compound literal keeps existing until the end of the function it was declared in.

这篇关于在C中获取临时(复合文字)参数的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆