Static variable or global variable?

 

Which is better and safer?

use static variable in OnTick() function or global variable?

 
  1. If the variable is used in multiple functions, there is no choice, it must be global.
  2. Otherwise make it static so it's only visible in the function.  Pass it to other functions if necessary.
 
Overweight:

Which is better and safer?

use static variable in OnTick() function or global variable?

Safer (not better)

int f()
{
  OnStart();
  
  return(5);
}

const int i = f();
const int j_global = i;

#define PRINT(A) Print(#A + " = " + (string)(A))

void OnStart()
{
  static const int j_static = i;
  
  PRINT(j_static);
  PRINT(j_global);
}


Result

j_static = 0
j_global = 0
j_static = 0
j_global = 5


It is necessary to understand well what potential problems can be when using static variables.

 
fxsaber: It is necessary to understand well what potential problems can be when using static variables.

You didn't show any. You showed that the order of initialization of global/static variables is undefined.

By the documentation they should only be initialized with constants and "= i;" is not one. IMO the compiler should reject any such code.

Reason: