Home > Net >  Do I always have to initialize a function pointer when declaring it?
Do I always have to initialize a function pointer when declaring it?

Time:03-12

Lets consider the next piece of code:

#include <iostream>

void print()
{
   std::cout << "I feel void" << std::endl;
}

void (*func)();
func = print;

This does not compile, since "func does not name a type". But I already declared about func's type. It's a function pointer that takes no arguments and returns void. Why do I need to name a type again?

CodePudding user response:

Do I always have to initialize a function pointer when declaring it?

No.

However, you cannot have expression statements such as assignments in namespace scope.

CodePudding user response:

you can do that in main! , you cant do that in namespaces:

void (*func)();
void print()
{
    std::cout << "I feel void" << std::endl;
}
int main(int argc, char* argv[])
{
    func = print;
    return 0;
}

but if you want do that before main execution , you can try below code(I prefer dont use this , but it's helpful sometimes):

#include <iostream>
void (*func)();
void print()
{
    std::cout << "I feel void" << std::endl;
}
class Initilizer
{
public:
    Initilizer()
    {
        init();
    }
    static void init()
    {
        func = ::print;
    }
};

Initilizer obj;

int main(int argc, char* argv[])
{
    func(); /*Test func*/
    return 0;
}


  •  Tags:  
  • c
  • Related