Are function pointers always initialized to NULL?

I am using MSVC, and it looks like the code below is not crashing, 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 looks like MSVC is initializing pointers to a NULL function, but if I build it on gcc on Linux, will it also be NULL? Is this regular or MSVC specific, can I rely on it being NULL, wherever I go?

thanks

+4
source share
1 answer

operate initialized to NULL because it is a global variable, and not because it is a pointer to a function. All objects with static storage duration (including global variables, file-level variables static and static variables in functions) are initialized to 0 or NULL if no initializer is specified.

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

Objects with a static storage duration (3.7.1) must be zero (8.5) before any other initialization occurs. Zero initialization and initialization with an expression constant are called collectively static initialization; all other initialization is dynamic initialization.

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

[EDIT # 2] . As Jeff M notes in a comment, it’s important to understand that auto-storage time variables (that is, “regular” local variables) are not automatically initialized to zero: if an initializer is specified, or they are assigned to values ​​by the constructor, they will initially contain random garbage (which was already in memory in this place). So it’s a good habit to initialize all variables - it cannot hurt, but it can help.

+17
source

All Articles