Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will function pointers always initialize to NULL?

Tags:

c++

c

I'm using MSVC and it seems like the code below does not crash and the function pointer is initialized to NULL by the compiler.

int (*operate)(int a, int b);
int add(int a, int b)
{
    return a + b;
}

int subtract(int a, int b)
{
    return a - b;
}

int main()
{


    if(operate) //would crash here if not NULL
    {
        cout << operate(5,5);
    }

    operate = add;
    if(operate)
    {
        cout << operate(5,5);
    }

    operate = subtract;
    if(operate)
    {
        cout << operate(5,5);
    }
    return 0;
}

So it seems MSVC initializes function pointers to NULL, but if I build this on gcc in Linux would it also be NULL? Is it conventional or MSVC specific, can I rely on it being NULL wherever I go?

Thanks

like image 989
jmasterx Avatar asked Oct 07 '10 00:10

jmasterx


1 Answers

operate is initialised to NULL because it is a global variable, not because it is a function pointer. All objects with static storage duration (which includes global variables, file-level static variables and static variables in functions) are initialised to 0 or NULL if no initialiser is given.

[EDIT in response to Jim Buck's comment:] In C++, this is guaranteed by clause 3.6.2/1 of the language standard, which begins:

Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization.

I expect the same behaviour is true of C, since C++ is designed to be compatible with it on most things, although I don't have the standard for it.

[EDIT #2] As Jeff M points out in a comment, it's important to realise that variables of automatic storage duration (that is, "ordinary" local variables) are not automatically zero-initialised: unless an initialiser is given, or they are assigned values by a constructor, they will initially contain random garbage (whatever was already sitting in memory at that location). So it's a good habit to initialise all variables -- it can't hurt but can help.

like image 164
j_random_hacker Avatar answered Sep 30 '22 15:09

j_random_hacker