Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the spec mean by the highlighted sentence in §3.3.7/1 item 5?

§3.3.7/1 item 5:

The potential scope of a declaration that extends to or past the end of a class definition also extends to the regions defined by its member definitions, even if the members are defined lexically outside the class (this includes static data member definitions, nested class definitions, and member function definitions, including the member function body and any portion of the declarator part of such definitions which follows the declarator-id, including a parameter-declaration-clause and any default arguments (8.3.6)).

Would it be possible to identify such a declaration in the first example given in this paragraph?

typedef int c;
enum { i = 1 };
class X {
    char v[i];
    int f() { return sizeof(c); }
    char c;
    enum { i = 2 };
};
like image 329
Ayrosa Avatar asked Dec 14 '25 08:12

Ayrosa


2 Answers

It looks as though it's saying, among other things, and in addition to the answer above, that given all the code outside that class definition, even if X::f were defined outside the class, like so:

typedef int c;
enum { i = 1 };
class X {
    char v[i];
    int f();
    char c;
    enum { i = 2 };
};

int X::f() {
    return sizeof(c);
}

that, in the context of the definition of X::f, c would refer to the member variable X::c, not the typedef above, because even though it kind of looks like it's being defined globally, f actually lives in X's scope.

like image 168
acwaters Avatar answered Dec 16 '25 22:12

acwaters


Yes. The declaration of the member c of the class X is visible inside the definition of f, even though lexically, it comes afterwards. This means that the sizeof expression applies to the member, and not to the type outside, which mean it will return 1, not whatever the size of int is (probably 4).

Also, the enum constant X::i should, according to this rule, be visible when the array v is declared, although this surprises me, and I would strongly suggest to avoid such code - sounds like a compiler bug or developer misunderstanding just waiting to happen.

Edit: Lightning Strikes in Orbit is probably right that the comment about parts of the declarator only applies to out-of-line definitions.

like image 37
Sebastian Redl Avatar answered Dec 16 '25 21:12

Sebastian Redl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!