2

Based on the explanation of https://en.cppreference.com/w/c/language/compound_literal:

The unnamed object to which the compound literal evaluates has static storage duration if the compound literal occurs at file scope and automatic storage duration if the compound literal occurs at block scope (in which case the object's lifetime ends at the end of the enclosing block).

But this piece of code compiles (and works) fine without warnings (all warnings on) in both gcc and clang:

#include <stdio.h>

typedef struct {int first; int second;} int_pair;

static int_pair *pair(int a, int b)
{
    return &(int_pair){a, b};
}

int main(void)
{
    int_pair *x = pair(1, 2);

    printf("%d %d\n", x->first, x->second);
    return 0;
}

As far as I understand, this piece of code is the same as:

static int_pair *pair(int a, int b)
{
    int_pair x = {a, b};

    return &x;
}

Which returns:

warning: function returns address of local variable [-Wreturn-local-addr]
     return &x;
David Ranieri
  • 39,972
  • 7
  • 52
  • 94

0 Answers0