Ancient_Hacker said:
A while back I had to recompile some old code, originally written by a
really good programmer, but one prone to use every trick in the book,
and then some.
There was a statement, something like this:
Result = ( Mode == 2 ? TwoWayFunc : FourWayFunc ) ( Param1,
Param2, Param3 );
... after a little headscratching I figured it out, but ... is this
legal in C? It compiled with an Microsoft C 2.6 or so compiler, but
of course that isnt much help.
Yes, assuming TwoWayFunc and FourWayFunc are functions of the same
type, and that the parameter list is valid for both.
Expressions of function type (not pointer-to-function type, function
type) are treated similarly to expressions of array type. An
expression of function type (such as the name of a function) is
implicitly converted to a pointer to the function, unless it's the
operand of a unary "sizeof" or "&" operator. (If it's the operand of
sizeof, it's a constraint violation; this rule makes "sizeof func"
illegal rather than an expression that yields the size of a function
pointer. If it's the operand of "&", the result is the address of the
function, the same result you'd get without the "&".)
An ordinary function call:
func(arg1, arg2)
invokes the function call operator. The left operand must be a
pointer-to-function. The conversion of "func" to a pointer occurs
before the function call operator is evaluated.
If func_ptr is an object of type pointer-to-function then this:
func_ptr(arg1, arg2)
works the same way, except that no implicit conversion was done on the
left operand.
In your expression, if TwoWayFunc and FourWayFunc are function names,
they're both implicitly converted to function pointers. The
expression ( Mode == 2 ? TwoWayFunc : FourWayFunc ) is evaluated
normally, and the result (either a pointer to TwoWayFunc or a pointer
to FourWayFunc) is used as the left operand of the function call
operator.
Once you understand how function names are handled, and how the
function call operator works, it's all perfectly straightforward.