1

There is this code:

void a() { }

// function parameter first defined as function, then as pointer to function
void g(void f() = a, void (*d)() = a) {
}

int main(){
   void (*z)() = a; // works ok
   //void z() = a; error: illegal initializer (only variables can be initialized)
   return 0;
}

In function parameter list you can define function parameter as a function or as pointer to function (see function g parameter list). However in main function only pointer to function version seems to work. Is there some way to define a function variable (not a pointer to function) in block scope (like the void f() = a variable in g function)?

4 Answers 4

2

You cannot have variables of function type in C++. You can either have pointers or references to functions, though:

typedef void (funtype)();

void call(funtype & f) { f(); } // OK, funtype & == void (&)()
void call(funtype * g) { g(); } // Also OK, funtype * == void (*)()

In some sense, you always call a function through a function pointer: An expression whose value is a function immediately decays to the corresponding function pointer. So in the above examples, f(), (*f)(), (**f)() and so forth are all valid ways of calling the function, and likewise for g. But passing by reference has the advantage that you can still get the function pointer explicitly by saying &f.

Sign up to request clarification or add additional context in comments.

Comments

0

The argument f of your function g is actually of function pointer type. Any function type argument is transformed to a function pointer type:

After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively.

However, that doesn't happen for a normal variable declaration. void z() = a; declares a function and then attempts to initialise it. You can't do this because a function is not a variable.

Comments

0

There is no such thing as a "function variable", it must be a pointer or a reference to a function. (Other languages probably simply hide the fact that the variable is a pointer or reference).

Comments

0

In void g(void f() = a), f is not a function type; it's a pointer to function. (Cf. void h(int x[3]), where x is a pointer to int). In void f() = a; f is, indeed, a function type and you cannot create a variable of a function type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.