I don't understand this:
(7.6.1) Two consecutive left square bracket tokens shall appear only when introducing an attribute-specifier. [Note: If two consecutive left square brackets appear where an attribute-specifier is not allowed, the program is ill formed even if the brackets match an alternative grammar production. —end note ] [Example: (slightly modified from source)
// ...
void f() {
int x = 42, y[5];
// ...
y[[] { return 2; }()] = 2; // error even though attributes are not allowed
// in this context.
}
What alternate grammar can [[
be used for? Would the example be valid if attributes didn't exist (and what does the example do)?
Grammar symbols are associated with attributes to associate information with the programming language constructs that they represent. Values of these attributes are evaluated by the semantic rules associated with the production rules.
Attribute and attribute are spelled identically but are pronounced differently and have different meanings, which makes them heteronyms.
Attribute grammar is a special form of context-free grammar where some additional information (attributes) are appended to one or more of its non-terminals in order to provide context-sensitive information. Each attribute has well-defined domain of values, such as integer, float, character, string, and expressions.
The example creates a simple lambda, which is directly called and will just return 2
. This will get the third element from the array and assign it to 2
. Could be rewritten as follows:
int foo(){ return 2; }
int y[5];
y[foo()] = 2;
Or even
int y[5];
auto foo = []{ return 2; }; // create lambda
y[foo()] = 2; // call lambda
Now, if attributes didn't exist, the example would of course be well-formed, because the section you quoted wouldn't exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With