Ruslan
Ruslan

Reputation: 19130

Declaring a structure and immediately instantiating it with cv-qualifier or storage duration specifier

Consider the following code:

static const struct X
{
    int a;
} x={1};

X y;

It compiles, and X appears to work in the declaration of y. But is it actually true that static const and similar cv-qualifiers and storage duration specifiers don't affect the definition of X? I.e. is the following exactly equivalent to the above?

struct X
{
    int a;
};
static const X x={1};

X y;

Upvotes: 1

Views: 28

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

Name X in declaration

static const struct X
{
    int a;
} x={1};

introduces type specifier struct X. Thus this declaration

X y;

is equivalent to

struct X y;

As for storage class specifiers then according to the C++ Standard (7.1.1 Storage class specifiers)

  1. ... The storage-class-specifier applies to the name declared by each init-declarator in the list and not to any names declared by other specifiers.

So in this declaration

static const struct X
{
    int a;
} x={1};

static is a storage class specifier of declarator x that is present in init-declarator x={1}

If you would use for example a typedef

typedef const struct
{
    int a;
} X;

then in this case type name X would indeed have qualifier const.

So if you will define for example

X x = { 1 };

then x will be a constant object. You will be unable to write

x.a = 2;

Nevertheless you may not specify a storage class specifier in a typedef because as it is said in the quote storage class specifiers may be specified only for init-declarators. However you may write

static X x = { 1 };

because the storage class specifier is applied to x that has type const X

Upvotes: 3

Related Questions