In-Class Initializers: Why the Bracket or Equals Restriction?
In C 11, in-class initializers must comply with a specific syntax: they must either be enclosed in curly braces or directly follow an equals sign (=). However, the use of parentheses is not permitted. Understanding the rationale behind this requirement is crucial.
Preventing Syntax Ambiguity
The restriction stems from the potential for syntax ambiguity. Consider the following class:
class AmbiguousSyntax { struct Overloaded; int Overloaded; int confusing(Overloaded); };
Line 4 is ambiguous if parentheses were allowed for in-class initializers. It could potentially be interpreted as either a declaration of a member function named "confusing" accepting a parameter of type "Overloaded" or a definition of an "int" member variable "confusing" initialized to the value of the data member "Overloaded."
Clarity through Brackets
By requiring curly braces for in-class initializers, C 11 removes this ambiguity. Modifying the previous example:
class AmbiguousSyntax { struct Overloaded; int Overloaded; int confusing{Overloaded}; };
Now, it's clear that "confusing" is an integer member initialized to the value of "Overloaded," as the use of parentheses for function parameters is not allowed.
This syntax restriction in C 11 ensures clear differentiation between function declarations and member variable declarations/initializations, thereby enhancing code readability and avoiding confusion in the interpretation of in-class initializers.
The above is the detailed content of Why Can't C 11 In-Class Initializers Use Parentheses?. For more information, please follow other related articles on the PHP Chinese website!