Best practice, global variables

Hi everyone, i've read a number of articles saying global variables are bad for good reason. I'm trying to stay away from them but its proving hard. I have a program with a number of variables that are populated from user input. The majority of them remain constant throughout the program.

I have a number of functions which use the variables for their parameters. I am passing the addresses of the variables to and from the functions but this is pretty cumbersome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <iomanip>
#include <vector>
#include <fstream>
#include <ctime>

using namespace std;

struct Axle {
    int aRef;
    float aWeight;
    float aPos;
    bool aFlag;
};

// Prototypes
void getVehicleDetails (vector<Axle>&vehicle, float &Span, float &inc, int &noAxles);
void createOutput (float &Span, float &inc);
void arrayDump(vector<Axle>&vehicle, int &noAxles);
void analyse(vector<Axle>&vehicle, int &noAxles);

// Main Prog
int main(){

    int noAxles = 0;
    float Span = 0, inc =0;
    vector<Axle> vehicle;

    getVehicleDetails(vehicle, Span, inc, noAxles);

    createOutput(Span, inc);
    
    arrayDump(vehicle, noAxles);

    analyse(vehicle, noAxles);

    return 0;
}

void getVehicleDetails(vector<Axle>&vehicle, float &Span, float &inc, int &noAxles){

    // Get user input to populate variables

}

void createOutput(float &Span, float &inc){

    // Creates an output file outing some variables
}


void arrayDump(vector<Axle>&vehicle, int &noAxles){

    // dump of variables after each iteration

}


void analyse(vector<Axle>&vehicle, int &noAxles){

    // Analysis - performs calcs after each iteration and calls the arrayDump each time
}


It would be a lot easier to create global variables that can be accessed from each function?

Can anyone advise on a best method?

Thanks
I suppose one way would be to write a class 'Car' that has all the variables and functions you need, then create a 'Car' object in main() and call its methods. You shouldn't bee too paranoid about this though.
Thanks dude,

just seems like i am creating variables in main and trying to keep track of them passing them back and forth between functions. Much easier to declare global variables that all functions can access.
Last edited on
Topic archived. No new replies allowed.