I'm writing my own game engine in C++ and I was wondering where should I initialize variables which I need every frame, for example, every time mouse pointer is getting moved, the coordinates of pointer position should be saved in a variable.
Should I initialize the variable for that globally or in the function where it always initializes the variable new? Where are the benefits and where are the disadvantages?
float offsetX
float offsetY
void mouse_callback(double posX, double posY) {
offsetX = posX - lastX;
offsetY = lastY - posY;
lastX = posX;
lastY = posY;
}
or
void mouse_callback(double posX, double posY) {
float offsetX = posX - lastX;
float offsetY = lastY - posY;
lastX = posX;
lastY = posY;
}
Variables should be defined as closely as possible to where they are used. The longer the distance between declaration and initialization, the more error prone the code will be.
A good thing about having the variables defined in the function, is that you can mark them as const
(!). Then you notify the readers of the code, that these variables will never change.
Remember that you write code for people and not for the compiler. For this simple use case, there will probably be no difference in memory nor speed - the compiler will be able to optimize away the variables.