c 语言中auto int x=1,在C中,&(int){1}是什么意思?

据我可以告诉这是一个

compound literal,它是C99的功能,它是

not standard C++,但是gcc和铛支持它作为一个扩展:

ISO C99 supports compound literals. A compound literal looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer; it is an lvalue. As an extension, GCC supports compound literals in C90 mode and in C++, though the semantics are somewhat different in C++.

Usually, the specified type is a structure. Assume that struct foo and

structure are declared as shown:

06000

Here is an example of constructing a struct foo with a compound

literal:

06001

This is equivalent to writing the following:

06002

在这种情况下,a的类型将指向int。希望这是原来的C代码,因为gcc文档说:

In C, a compound literal designates an unnamed object with static or automatic storage duration. In C++, a compound literal designates a temporary object, which only lives until the end of its full-expression.

因此在C中取地址可能是一个坏主意,因为对象的生命周期在完整表达式的末尾结束。虽然,它可能是C代码,只是依赖于未定义的行为。

这是其中使用正确的标志真正帮助很多,在gcc和clang使用-pedantic将产生一个警告和错误,例如gcc说:

warning: ISO C++ forbids compound-literals [-Wpedantic]

auto a = &(int) { 1 };

^

error: taking address of temporary [-fpermissive]

如果我们使用-fpermissive是gcc它确实允许这个代码编译。我不能在现代版本中用任何标志来构建这个代码,虽然旧版本似乎允许使用-Wno-address-of-temporary。我想知道gcc是否允许这作为一个remnant of an old extension。

注意,问题Cryptic struct definition in C有一个非常有趣(取决于你有趣的定义)复合字面量的使用。

假设Schism is correct和this question是原始源,那么在示例中的代码中的使用:

if (setsockopt(server_connection.socket, SOL_SOCKET, SO_REUSEADDR, &(int) { 1 }, sizeof(int)) < 0) {

是在C99和C中的有效使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值