Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a typedef of a function be used to define a function?

From § 8.3.5.11 of ISO/IEC 14882:2011(E):

A typedef of function type may be used to declare a function but shall not be used to define a function

The standard goes on to give this example:

typedef void F();
F fv; // OK: equivalent to void fv();
F fv { } // ill-formed
void fv() { } // OK: definition of fv

What motivates this rule? It seems to limit the potential expressive usefulness of function typedefs.

like image 872
Shea Levy Avatar asked Jul 25 '13 04:07

Shea Levy


2 Answers

Though this question is about C++, but since C++ inherits typedef and function pointer from C, so an explanation of the same question in C can be used in here. There's a formal explanation for C.

Rationale for International Standard - Programming Languages C §6.9.1 Function definitions

An argument list must be explicitly present in the declarator; it cannot be inherited from a typedef (see §6.7.5.3). That is to say, given the definition:

typedef int p(int q, int r);

the following fragment is invalid:

p funk // weird
{ return q + r ; }

Some current implementations rewrite the type of, for instance, a char parameter as if it were declared int, since the argument is known to be passed as an int in the absence of a prototype. The Standard requires, however, that the received argument be converted as if by assignment upon function entry. Type rewriting is thus no longer permissible.

like image 121
Yu Hao Avatar answered Sep 19 '22 18:09

Yu Hao


It's probably mostly historical reasons. typedef was a relatively late addition to C, and was tacked onto the existing language (and caused a few problems for the parsing phase of compilers).

Also, a function definition has to define the names of the parameters, if any. A function type includes the function's return type and parameter types, but not its parameter names. For example, these:

void (int)
void (int x)
void (int y)

are three ways of writing the same function type. If you had:

typedef void func_t(int);

then this hypothetical definition:

func_t some_func { }

wouldn't define a name for its int parameter. I'm not sure how that could have been resolved in a reasonable manner. It would be possible, I suppose, but it was never done.

But the bottom line is probably just that Dennis Ritchie either didn't think it was worth the effort to define how a typedef could be used in a function definition, or he simply didn't think of it.

like image 22
Keith Thompson Avatar answered Sep 18 '22 18:09

Keith Thompson