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; }
totalas a member variable anddepositandwithdrawas member functions.