Scotty Tollison
Scotty Tollison

Reputation: 25

Is there a better way to define a global variable?

I'm looking for a better way to define a global variable. This is just a small banking app to practice using functions. Is this the correct way to define the variable according to C++ standards? I'm not 100% sure on this one. I defined it outside of main(), but if I remember correctly, this is a no no. I tried creating classes, I tried creating paramaters for the functions, this is the only way I could figure out how to get the variable to all the functions.

// banking.cpp : This file contains the 'main' function. Program execution begins and ends there.


#include <iostream>

using namespace std;

int total = 100;


void menu();
int deposit();
int withdraw();

int main()
{
    menu();
    return 0;
}

void menu()
{

    int selection;
    cout << "your total money right now is $" << total << endl;
    cout << "select 1 for deposit." << endl;
    cout << "select 2 for withdraw" << endl;
    cin >> selection; 

    switch (selection)
    {
    case 1:
        deposit();
        break;
    case 2:
        withdraw();
        break;

    }

}

int deposit()
{
    int depositAmount;

    cout << "your current total is $" << total << endl;
    cout << "how much would you like to deposit? " << endl;
    cin >> depositAmount;

    total = depositAmount + total;

    cout << "your new total is $" << total << endl;
    cout << "you will be returned to the main menu..." << endl;

    menu();
    
    return total;
}

int withdraw()
{
    int withdrawAmount;
    
    cout << "your current total is $" << total << endl;
    cout << "how much would you like to withdraw? " << endl;
    cin >> withdrawAmount;

    total = total - withdrawAmount;

    cout << "your new total is $" << total << endl;
    cout << "you will be returned to the main menu..." << endl;

    menu();

    return total;
}

Upvotes: 0

Views: 164

Answers (2)

Onur Onder
Onur Onder

Reputation: 336

If you need to store a state shared across functions, you probably want to create a class/struct, with members as the data you want to share.

class MyClass
{
public:
   void menu();
   int deposit();
   int withdraw();

private:
   int total = 100;
};

Then use this class whenever you want to run your logic.

int main()
{
    MyClass myclass;
    myclass.menu();
    return 0;
}

Upvotes: 3

Dawid Wysocki
Dawid Wysocki

Reputation: 61

You can pass total to a function with & in front of it. It is known as reference in C++ and you can modify given object inside a function, not only it's copy. Examples. And in your code:

int deposit(int &total) { ...your code... }

Overall I don't think calling menu inside every function is a good idea. With each function call you push it to a stack, which takes extra memory. Changing deposit and withdraw to void and using while(1) loop inside of main() to call menu() would be much better.

Upvotes: 2

Related Questions