C++/Function/Function Variables

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Function local variable

<source lang="cpp">

  1. include <iostream>

using namespace std; void printMessage(void); int main () {

  char choice;
  do {
     cout << "Enter Q to quit, any other character to continue: ";
     cin >> choice;
     if (choice == "Q")
        cout << "Input stopped";
     else
        printMessage(); 
     } while (choice != "Q");
  return 0;

} void printMessage (void) {

  int times = 0;
  times++;
  cout << "This function called " << times << " times\n";

}

      </source>


Returning a Pointer to a Static Local Variable

<source lang="cpp">

  1. include <iostream>

using namespace std; char * setName(); int main (void) {

  char* str = setName();
  cout << str;
  return 0;

} char* setName (void) {

  static char name[80]; 
  cout << "Enter your name: ";
  cin.getline (name, 80);
  return name;

}

      </source>


Static function variable

<source lang="cpp">

  1. include <iostream>

using namespace std; void printMessage(void); int main () {

  char choice;
  do {
     cout << "Enter Q to quit, any other character to continue: ";
     cin >> choice;
     if (choice == "Q")
        cout << "Input stopped";
     else
        printMessage(); 
     } while (choice != "Q");
  return 0;

} void printMessage (void) {

  static int times = 0;
  times++;
  cout << "This function called " << times << " times\n";

}

      </source>