Most vexing parse explained

The most vexing parse is a counterintuitive form of syntactic ambiguity resolution in the C++ programming language. In certain situations, the C++ grammar cannot distinguish between the creation of an object parameter and specification of a function's type. In those situations, the compiler is required to interpret the line as a function type specification.

Occurrence

The term "most vexing parse" was first used by Scott Meyers in his 2001 book Effective STL.[1] While unusual in C, the phenomenon was quite common in C++ until the introduction of uniform initialization in C++11.[2]

Examples

C-style casts

A simple example appears when a functional cast is intended to convert an expression for initializing a variable:

void f(double my_dbl)

Line 2 above is ambiguous. One possible interpretation is to declare a variable i with initial value produced by converting my_dbl to an int. However, C allows superfluous parentheses around function parameter declarations; in this case, the declaration of i is instead a function declaration equivalent to the following:

// A function named i takes an integer and returns an integer.int i(int my_dbl);

Unnamed temporary

A more elaborate example is:struct Timer ;

struct TimeKeeper ;

int main

The line TimeKeeper time_keeper(Timer);

is ambiguous, since it could be interpreted either as

  1. a variable definition for variable of class, initialized with an anonymous instance of class or
  2. a function declaration for a function that returns an object of type and has a single (unnamed) parameter, whose type is a (pointer to a) function[3] taking no input and returning objects.

The C++ standard requires the second interpretation, which is inconsistent with the subsequent line 10 above. For example, Clang++ warns that the most vexing parse has been applied on line 9 and errors on the subsequent line 10:[4] $ clang++ time_keeper.cc timekeeper.cc:9:25: parentheses were disambiguated as a function declaration [-Wvexing-parse] TimeKeeper time_keeper(Timer);

Notes and References

  1. Book: Meyers, Scott. Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library. Addison-Wesley. 2001. 0-201-74962-9. Scott Meyers.
  2. Web site: Coffin. Jerry. 29 December 2012. c++ - What is the purpose of the Most Vexing Parse?. live. https://archive.today/20210117023312/https://stackoverflow.com/questions/14077608/what-is-the-purpose-of-the-most-vexing-parse/14077852%2314077852. 17 January 2021. 2021-01-17. Stack Overflow.
  3. According to C++ type decay rules, a function object declared as a parameter is equivalent to a pointer to a function of that type. See Function object#In C and C++.
  4. Web site: Lattner. Chris. 5 April 2010. Amazing Feats of Clang Error Recovery. dead. https://web.archive.org/web/20200926165432/https://blog.llvm.org/posts/2010-04-05-amazing-feats-of-clang-error-recovery/. 26 September 2020. 2021-01-17. LLVM Project Blog. The Most Vexing Parse.