c - 复合文字的生命周期

标签 c gcc clang language-lawyer compound-literals

6.5.2.5p5

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.

我将此处的“封闭 block ”解释为“最里面的封闭 block ”是否正确? (因为如果它不是最里面的,那是哪一个?) Why are gcc and clang behaving as if the lifetime of a literal were its enclosing function?

例子:

long foo(long*);

void call_foo()
{
    {foo(&(long){42});}
    {foo(&(long){42});}
    {foo(&(long){42});}
    {foo(&(long){42});}
}

//for comparison

void call_foo2()
{
    {long x=42;foo(&x);}
    {long x=42;foo(&x);}
    {long x=42;foo(&x);}
    {long x=42;foo(&x);}
}

gcc/clang 在 -O3 生成的代码:

call_foo:
  sub rsp, 40
  mov rdi, rsp
  mov QWORD PTR [rsp], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+16]
  mov QWORD PTR [rsp+16], 42
  call foo
  lea rdi, [rsp+24]
  mov QWORD PTR [rsp+24], 42
  call foo
  add rsp, 40
  ret
call_foo2:
  sub rsp, 24
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  add rsp, 24
  ret

最佳答案

这似乎没有任何充分的理由。我只想称它为编译器错误。

关于c - 复合文字的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47691857/

相关文章:

计算可执行文件中的函数调用次数

c - 如何使用标准用户捕获 TCP/IP 数据包

c - GCC 优化标志的顺序

c++ - 如何在 64 位 Ubuntu 18.04 上使用 64 位 clang v8 构建 32 位 libc++?

c++ - 混合使用 constexpr 和 const?

c - C 中的 fopen 出现段错误? (不太确定导致错误的原因)

linux - g++ 默认 header 包含列表

c++ - g++ 和 gcc 4.8 找不到 null_ptr?

memory-management - 为什么 clang 的 `-O3` alloca 比 g++ 快 2 倍

c - 带按钮的内部上拉电阻如何设置?