1

I discovered few days ago Compound literals in the answer How do I use setsockopt(SO_REUSEADDR)?

So I tried to compile simple code :

#include <stdio.h>
int main()
{
    int * ptr = &(int) {3};
    printf("%d\n", *ptr);
    return 0;
}

Using gcc 4.9.1, it build and works as expected, it print "3" and valgrind doesnot report memory corruption.

However using g++ 4.9.1, it does not build :

$ g++ main.c 
main.c: In function ‘int main()’:
main.c:4:23: error: taking address of temporary [-fpermissive]
  int * ptr = &(int) {3};
                       ^

Is there is a way (like an g++ option) to support Compound literal ?

Community
  • 1
  • 1
mpromonet
  • 11,326
  • 43
  • 62
  • 91
  • g++ supports compound literals fine, it just doesn't let you take the address of one, which is sensible. It also doesn't let you take the address of other kinds of literal, e.g. `int* p = &3;`, which is also sensible. What's wrong with saying `int i = (int){3}; printf("%d\n", i);` instead of trying to take its address? – Jonathan Wakely Aug 13 '14 at 18:59

1 Answers1

1

In C language compound literals are lvalues. It is perfectly legal to take address of a compound literal in C. In C a local compound literal lives to the end of its enclosing block.

Meanwhile, GCC brings over compound literals to C++ (as a non-standard extension) with a number of significant changes. They are brought over as temporary objects. It is illegal to take address of a temporary object in C++. The lifetime of compound literals in C++ is also consistent with lifetime of temporaries - they live to the end of the expression.

AFAIK, there's no way to make GCC's C++ compound literals to behave as their C counterparts.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • @dyp: You are right. But the OP seems to know that compound literals are supported in GCC's version of C++ as a non-standard extension. – AnT stands with Russia Aug 13 '14 at 22:59
  • Interesting. You could also add a link to the [gcc documentation: compound literals (and their semantics in C++)](https://gcc.gnu.org/onlinedocs/gcc/Compound-Literals.html) – dyp Aug 13 '14 at 23:24