C++/Function/Function Variables

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

Function local variable

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


Returning a Pointer to a Static Local Variable

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


Static function variable

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