Why does gcc compile this code for the GNU C++ , but not compile for GNU C++11 ?

 #include <iostream> int main() { char *s = "string"; std::cout << s[[]{ return 1; }()]; } 
  • And what is the compilation error? - pavel
  • @pavel expected primary expression before ')' token - IGORb
  • How do you compile in gnu ++ mode? @pavel, I have this: pastebin.com/qYVWNqNu - PinkTux
  • @PinkTux in the compiler settings there is a choice - IGORb
  • Where do g++ have settings? Command line keys - I know, I don’t remember the settings. - PinkTux

1 answer 1

Because it is forbidden by the C ++ 14 standard (the newer version of the draft is available by reference)

[dcl.attr.grammar] p6 Two consecutive left square bracket tokens. The note is not allowed, it’s not a problem. - end note]

There is even an example:

 y[[] { return 2; }()] = 2; // error even though attributes are not allowed // in this context. 

Well, the first line is not very good either, it should be like this:

 const char *s = "string"; 
  • What standard? And in GNU C++ why does it compile? - IGORb
  • And a little more about these attributes do not share - simple language :)? - Harry
  • @IGORb, C ++ Standard 14. I believe that in version 11 this prohibition was already attributes appeared in version 11. - ixSci
  • @Harry, but for now there is nothing to share. There are a couple of auxiliary attributes that help mark different parts of the program for the compiler. Like [[noreturn]] , it says that the function never executes return : it can help the compiler with optimization, the deprecated attribute, to mark outdated functions and so on. At the approach of the attributes to mark variables that are not used consciously and fallthrough for case'ov select. So far this is all just a try of a pen and far from what is in C #, where attributes help a lot of interesting things to do. - ixSci
  • @IGORb, did not fully answer your question: if somewhere this code is compiled. This is a compiler error. Under no circumstances should it compile. - ixSci