Graznarak Graznarak - 3 months ago 21
C++ Question

Clang and GCC accept questionable sizeof

I have compilers that disagree on sizeof. For the following code, Clang and GCC will compile it, but other compilers that I have to use fail claiming "illegal sizeof operand". My reading of the standard says this is illegal, since

sizeof
can only take an expression (I don't think that S::a is an expression) or a type-id, but it is unusual for GCC and Clang to both be wrong. I can obviously replace it with
sizeof(S().a)
, which works with all my compilers.

struct S
{
int a[32];
int b;
int c;
int d[32];
};

int main()
{
return sizeof(S::a);
}


Are Clang and GCC wrong, or am I misreading the standard?

Answer

§ 5.1.1 [expr.prim.general] 13

An id-expression that denotes a non-static data member or non-static member function of a class can only be used:

— as part of a class member access (5.2.5) in which the object expression refers to the member’s class[63] or a class derived from that class, or

— to form a pointer to member (5.3.1), or

— if that id-expression denotes a non-static data member and it appears in an unevaluated operand [Example:

struct S {
    int m;
};

int i = sizeof(S::m);      // OK
int j = sizeof(S::m + 42); // OK

-end example]