Why the Direct Initialization Syntax is Forbidden for Class Data Members
C class data members cannot be initialized using the direct initialization syntax (expression-list) due to potential parsing ambiguities. This is evident in the example provided:
class test { private: int s(3); // Compiler error };
The compiler raises errors:
According to C Standards, data members can only be initialized using the following syntax:
Reasons for the Restriction
The direct initialization syntax was intentionally omitted for class data members to avoid ambiguity. Parsing the following declarations could be challenging:
struct S { int i(x); // data member with initializer? static int x; }; struct T { int i(x); // member function declaration? typedef int x; };
If the direct initialization syntax were allowed, it would be unclear whether int i(x) represents a data member with an initializer or a member function declaration. This ambiguity would also affect templates.
To resolve this parsing problem, the C Standards Committee decided to prohibit the direct initialization syntax for class data members and reserve it for function declarations and local variables.
The above is the detailed content of Why is Direct Initialization Syntax Forbidden for Class Data Members in C ?. For more information, please follow other related articles on the PHP Chinese website!