Global vs Local Variable Declaration - Programming

For Global Variables

Key: Avoid using global.

Improper usage of global variables will result in poor program design. Here are some of the poor side effects that come from improper use of global variables:

  • Break modularity
  • Buggy codes
  • Messy and very confusing code – a.k.a. spaghetti code
  • Difficult to debug and maintain
  • Error prone

Here are some good global variables:

int LeftEyePort = PORT1;
int RightEyePort  = PORT2;
float WheelDiameter = 10.25;	
float EncPerCM =  360.0 / (WheelDiameter * PI);

int main( ) {
	....
}

Unless your robot can change the wheel diameter, or the type of devices connected to ports while it is running, it makes sense to declare them as const global variables.

For Example:

const int LeftEyePort = PORT1;
const int RightEyePort  = PORT2;
const float WheelDiameter = 10.25;	
const float EncPerCM =  360.0 / (WheelDiameter * PI);

For Local Variables

  • Try restricting usage of a single letter for “localized” simple counter.

e.g.

for ( int i=0 ; i< 10; i++) {
          .... 
     }

Do not use “i” to represent something with an important context other than a simple counter.

e.g. do not use “e” to represent encoder value.

  • Should pertain to what it represents; e.g., use “totalEncoder” to represent the total encoder value instead of, e.g. , X.
  • Prefix the variable with the data type, such as:
int  iValue;
float fValue;  
double dValue;
  • Do not use leading “_”. By convention, variables prefixed with “_” are used for some very special purpose like “directives”. A directive construct is used to specify how a compiler should process its input. This will be discussed in another article. If you are not familiar with directives, you are recommended “not to” use leading “_” as part of your variable names.
  • Maximize readability:
    • Use Camel style for long names, e.g., encoderPerCM, encPerRotation. Some programmers like to use “_”, such as encoder_per_cm.