Global variables can appear before any function. - C++ Function

C++ examples for Function:Global Variable

Description

Global variables can appear before any function.

Demo Code

#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;
}

Result


Related Tutorials