-1

I know that using Global Variables in programming may create lots of problems in long term , like , Bugs , Lags and more . I am working on a program which has more than 5 functions which need to access global variables something like this.

int Name;
int Age;
int Weight;
String EyeColour;

void AddValues(int N, int A , int W , String EC){ Name = N; Age = A; Weight = W; EyeColour = EC; }

// All the functions below use those Global Variables

void function2(){ ... }

void function2(){ ... }

void function3(){ ... }

void function4(){ ... }

void function5(){ ... }

But according to this article

I should avoid using global variables to avoid future problems so I wrapped them up inside a struct. Like this.

struct Person{

int Name; int Age; int Weight; String EyeColour;

}

Now my main question is, should I declare the structure variable globally? Will it avoid the problems which could be created by global variables ?

If I declare the struct variable globally will it be equivalent to declaring variables globally instead of the structure?

Or

Should I declare the structure variable inside all the functions instead of declaring globally?

So that all functions can work flawlessly without any global variable problems.

1 Answers1

1

Create a class from the 4 variables (I don't have a compiler at hand, so forgive any compiler errors):

class Person
{
public:
    void Person(int N, int A , int W , String EC);

private: int Name; int Age; int Weight; String EyeColour; }

Create the implementation of Person in the Person.cpp file.

About the functions, if they only relay (or mostly rely) on the 4 properties (Name, Age, Weight, EyeColor), make the a method (function) inside the class.

Decide if a function should be in a method depends upon many thing, but the most important question is: does it belong (well enough) to the class or not?

Now in the Arduino.ino you can make one instance (or more if you need more).

Person _person;

Preferably, I add an underscore for global variables (and instance variables).

Also, I would avoid using String as changing it will cause dynamic memory allocation changes, which can be very bad in a 2K SRAM system. Try to make constant string arrays (with a max length).

Michel Keijzers
  • 13,014
  • 7
  • 41
  • 58