C 's Most Vexing Parse
In C , the way a code snippet is parsed can lead to unexpected behavior. One infamous example is known as the "most vexing parse."
The Enigma of Function Declarations
Consider the following code:
widget w(gadget(), doodad());
At first glance, it appears to declare a variable named w of type widget. However, this code actually defines a function named w that takes two arguments.
Argument Decay and Pointer Casting
In a function declaration, arguments of type array decay into pointers to the first element, and arguments of type function decay into function pointers. Thus, the equivalent declaration of w is:
widget w(gadget(*)(), doodad(*)());
This means the function w takes as its first argument a pointer to a function that takes no arguments and returns a gadget. It also takes a second argument, a pointer to a function that takes no arguments and returns a doodad. The function itself returns a widget.
Additional Complexities
The "most vexing parse" becomes even more confusing in cases like the following:
widget w(gadget(x));
If x is already a variable, how can this be interpreted as a function declaration? The answer lies in the fact that in C , you can use extra parentheses when declaring variables. Thus, gadget x; and gadget (x); both declare the same variable named x. The code above is therefore a declaration of a function that takes a first argument of type gadget named x, and returns a widget.
The above is the detailed content of What\'s C \'s \'Most Vexing Parse\' and How Does It Mislead Function Declarations?. For more information, please follow other related articles on the PHP Chinese website!