3 ms·
The "type first" declaration syntax is a source of much wailing and gnashing of teeth when it comes to trying to parse C++. See the "most vexing parse" [1]. [1
by Sharlin 4y ago
The "type first" declaration syntax is a source of much wailing and gnashing of teeth when it comes to trying to parse C++. See the "most vexing parse" [1].
[1] https://en.wikipedia.org/wiki/Most_vexing_parse https://en.wikipedia.org/wiki/Most_vexing_parse
- tsimionescu 4y agoThe most vexxing parse was a huge problem in C++ and a very niche problem in C not because of "type first" declaration syntax, but because C++ constructor calls in variable initialization are essentially identical to function declarations. This is a big reason why Java or C#, also type-first syntax languages, have no such ambiguity. The two examples on Wikipedia are both caused by this, even though it's not explicitly spelled out: int i(int(my_dbl)); // two calls to int's constructor // in Java/C# style syntax: int i = new int(new int(my_dbl)); //no ambiguity TimeKeeper time_keeper(Timer()); // in Java/C# style syntax: TimeKeeper time_keeper = new TimeKeeper(new Timer()); C++ could have also chosen to reserve a keyword for initialization even for in-place values, just like they did with `new`, but they chose to re-use function call syntax instead. I would also say that just moving the type after the variable name doesn't fully solve the issue - it's the : syntax for initialization that does this. Here is a hypothetical C++ where the syntax remained the same as today, but (return) type was moved at the end of a declaration: typedef double my_dbl; typedef int i; foo (my_dbl double ) void { i int (int(my_dbl)); //unambigous: i is an int initialized with an int constructed from my_dbl f (double) int; //unambigous: f is a function from double to int g int (my_dbl); //unambigous: g is an int constructed from my_dbl bar((my_dbl)i); //ambigous: calling bar with i cast to double, or calling it with a function from my_dbl to i (double to int)? }
- DerekL 4y agoSimilar problems happen even in C. Suppose you have this line inside a function: X *y; Are you declaring a pointer, or are you performing multiplication? It depends on what “X” is.
- tsimionescu 4y agoTrue, though in this case as well, just replacing type first to type last would presumably lead to `y *X` which doesn't help so much in resolving ambiguity.