c++ - Will function pointers always initialize to NULL? -
i'm using msvc , seems code below not crash , function pointer initialized null compiler.
int (*operate)(int a, int b); int add(int a, int b) { return + b; } int subtract(int a, int b) { return - 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 seems msvc initializes function pointers null, if build on gcc in linux null? conventional or msvc specific, can rely on being null wherever go?
thanks
operate
initialised null because global variable, not because function pointer. objects static storage duration (which includes global variables, file-level static
variables , static
variables in functions) initialised 0 or null if no initialiser given.
[edit in response jim buck's comment:] in c++, guaranteed clause 3.6.2/1 of language standard, begins:
objects static storage duration (3.7.1) shall zero-initialized (8.5) before other initialization takes place. zero-initialization , initialization constant expression collectively called static initialization; other initialization dynamic initialization.
i expect same behaviour true of c, since c++ designed compatible on things, although don't have standard it.
[edit #2] jeff m points out in comment, it's important realise variables of automatic storage duration (that is, "ordinary" local variables) not automatically zero-initialised: unless initialiser given, or assigned values constructor, contain random garbage (whatever sitting in memory @ location). it's habit initialise variables -- can't hurt can help.
Comments
Post a Comment