Petr Skocik
Petr Skocik

Reputation: 60163

Global pointer to a statically allocated struct

I want a global pointer to a statically allocated struct.

This compiles

struct sa{
    int a, b;
    char const* c;
};
struct sa* sap = &(struct sa){42,43,"x"};

but is it legal & portable C, or do I have to do something like?:

static struct sa x = {42,43,"x"};
struct sa* sap2  = &x;

Upvotes: 1

Views: 168

Answers (2)

JustinCB
JustinCB

Reputation: 523

It's legal when used in the global scope, but it takes the address of a literal, so if you try to change the value, you will get an error. Although, reading your question, since a literal is static, it might work for you. As far as good coding practices are concerned, you might want to use

const struct sa* sap = &(struct sa){42,43,"x"};

or, preferably,

static struct sa x = {42,43,"x"}; const struct sa* sap2 = &x;

Upvotes: 0

Petr Skocik
Petr Skocik

Reputation: 60163

Apparently, according to http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf, 6.5.2.5 Compound literals, 5:

The value of the compound literal is that of an unnamed object initialized by the initializer list. 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.

it's legal when used in the global scope.

Thanks WhozCraig for letting me know the name of the construct so I could look it up. ;)

Upvotes: 1

Related Questions