C++ examples for Function:Global Variable
Global variables can appear before any function.
#include <iostream> using namespace std; int do_fun(); int third_fun(); // Prototype discussed later. int main()/*from www. ja va 2s.c o m*/ { cout << "No variables defined in main() \n\n"; do_fun(); // Call the first function. return 0; } float sales, profit; // Two global variables. int do_fun() { sales = 20000.00; // This variable is visible from this point down. profit = 5000.00; // As is this one. They are both global. cout << "The sales in the second function are " << sales << "\n"; cout << "The profit in the second function is " << profit << "\n\n"; third_fun(); // Call the third function to show that globals are visible. return 0; } int third_fun() { cout << "In the third function: \n"; cout << "The sales in the third function are " << sales << "\n"; cout << "The profit in the third function is " << profit << "\n"; return 0; }