Search code examples
cdesignated-initializer

Using variable being initialized in a designated initializer


Am I allowed to use a variable being initialized inside a designated initializer?

Consider the following listing:

struct A {
    int a;
    int * const a_ptr;
};

struct A foo(int a) {
    struct A result = {
        .a = a,
        .a_ptr = &result.a
    };

    return result;
}

demo

Am I allowed to use result in this designated initializer expression? Is this behavior defined? Is this code portable?

Update

My bad, the example contains a potential stack corruption. The listing should be:

struct A {
    int a;
    int * const a_ptr;
};

void foo(int a) {
    struct A result = {
        .a = a,
        .a_ptr = &result.a
    };

    bar(&result);
}

Solution

  • The initialization by itself is fine.

    At the time result is declared, its address (as well as the addresses of its fields) is constant. So it is safe to use &result.a in the initializer of result.

    What is a problem however is that you're returning a copy of this structure. This copy contains the address of a local variable that no longer exists, so attempting to use the value of the a_ptr member of the returned struct will trigger undefined behavior.