How to avoid global variables

Hello.

In my program I have tons, seriously, tons of global variables!
I've thought of some ways so as to decline their number.
Basically, I use all this global variables because I have the need to use them in multiple functions, this could be avoided if I used them as arguments when calling the functions which use the corresponding global variable. This is an idea, but it doesn't solve the problem completely.

For example, a function that shows me that in the GUI a button was pressed, and it is just a function (it doesn't take any arguments), cannot take as an argument the variable because it is meaningless!
To put it in other words, if I have such a function, which is not actually called from another function:
1
2
3
void on_button_3_clicked(){
   //code here
}

, and inside this function I need to do a check, i.e. to check if something is true or false (which is declared on a global variable), then I don't know how can I avoid this.... :/ Any ideas?
Step 1: group all your global variable declarations together.
Step 2: add struct globalData { before the first and }; after the last.
Step 3: add parameter globalData &datas to each function.
Step 4: in the first step of your main, declare globalData mahGlobals. Then pass it to each function.

Easy? Definitely. Pretty? Mmnnno. Efficient? Doubt it. Snazzy? That's not a word.
Last edited on
First of all it's nothing wrong to have global constants.

When you create a function think about what data it needs to do what it's supposed to do. Pass that data as arguments to the function.

If it's mouse buttons that on_button_3_clicked receives you might want to pass the position of the mouse where the click was made. If it should change some part of the GUI it needs access to that part. If on_button_3_clicked is a class member function you already have the implicit parameter this, and you can hopefully use the member variables to do what you have to do.
Thanks for the answers, what I really need to do here is to avoid loading all the global variables because some of them are useless unless the user does some specific actions. For example, I have a mainwindow.cpp file from which the user can do many actions. Let's say actions A, B or C. If user opens the program in order to do action A, then the program, regardless on what the user wants to do, will load also all the global variables which will be used in case user does action B and C, but he doesn't, so this is meaningless, so that's what I consider being wrong by using global variables!

If anyone has anything to add, thanks!
Topic archived. No new replies allowed.