Roman Kwaśniewski
Roman Kwaśniewski

Reputation: 483

Function pointer initialization with function declaration - is it possible?

Is it possible to initialize function pointer with function declaration in C++? I mean, something like this:

void (*pointer)(void) = &( void function(void) );

or this:

void (*pointer)(void) = void function(void);

Upvotes: 2

Views: 1872

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 311058

An initializer may not be a declaration. It does not make sense. You already specified the type of the pointer when you declared it.

If you declare a pointer and want to initialize it when you have to assign it some value.

Here is a demonstrative program. It uses an array of function pointers (to be more interesting).

#include <iostream>

void f1()
{
    std::cout << "Hello ";
}

void f2()
{
    std::cout << "Roman Kwaśniewski";
}

void f3()
{
    std::cout << '\n';
}

int main()
{
    void ( *fp[] )() = { f1, f2, f3 };

    for ( auto &func : fp ) func();
}

The program output is

Hello Roman Kwaśniewski

Pay attention to that you need not to specify for example &f2 as initializer because a function designator is implicitly converted to pointer.

Though for example this initialization is also correct

    void ( *fp[] )() = { f1, %f2, f3 };

and is equivalent to the previous one.

Upvotes: 0

Peter
Peter

Reputation: 36617

No, since a pointer - including a function pointer - must be initialised using an expression. A function declaration is not an expression.

However, an expression can be composed using previously declared functions (or variables) in the compilation unit (aka source file)

void function();     //  declare the function, defined elsewhere

void (*pointer)() = function;   //  function name in an expression is converted to a function pointer

It is possible (not recommended for readability purposes) to combine the two in one declaration of multiple variables.

void function(), (*pointer)() = function;

Upvotes: 0

It's almost possible, you just have to reverse the order: declare the function first, and then initialise the pointer with its address:

void function(), (*pointer)() = &function;

[Live example]

However, I consider this ugly, unreadable code, and would never suggest actually using it. So, my answer is: "It's possible, but should never be done." (I can imagine it being excusable in certain situations involving macros, but that's about it).

Upvotes: 1

Vittorio Romeo
Vittorio Romeo

Reputation: 93324

No, as any variable in C++ (including function pointers) has to be initialized with an expression, and a function declaration is not an expression.

You might want to use a captureless lambda expression instead:

void (*pointer)() = []{ std::cout << "hello world\n"; };

Upvotes: 1

Related Questions