C++ Tutorial/Language Basics/global variable

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

Global class variable

<source lang="cpp">#include<iostream.h> class test {

 int i;

public:

   test()
   {
     i=25;
     for(int ctr=0; ctr<10;ctr++)
     {
       cout<<"Counting at"<<ctr<<"\n";
     }
   }
   ~test(){};

}; test anObject; main() {

 return 0;

}</source>

Counting at0
Counting at1
Counting at2
Counting at3
Counting at4
Counting at5
Counting at6
Counting at7
Counting at8
Counting at9

Global variables are known throughout the entire program and may be used by any piece of code.

<source lang="cpp">#include <stdio.h>

void func1(void), func2(void);

int count;

main(void) {

 count = 100;   
 func1();   
 return 0; 

}

void func1(void) {

 int temp;   
    
 temp = count;   
 func2();   
 printf("count is %d", count); /* will print 100 */   

}

void func2(void) {

 int count;   
    
 for(count=1; count<10; count++)   
   putchar(".");   

}</source>

Use a global variable

<source lang="cpp">#include <iostream> using namespace std; void func1(); void func2(); int count; // This is a global variable. int main() {

 int i; // This is a local variable
 for(i=0; i<10; i++) {
   ::count = i * 2;
   func1();
 }
 return 0;

} void func1() {

 cout << "count: " << ::count; // access global count
 cout << "\n";
 func2();

} void func2() {

 int count;
 for(count=0; count<3; count++)
    cout << ".";

}</source>

count: 0
...count: 2
...count: 4
...count: 6
...count: 8
...count: 10
...count: 12
...count: 14
...count: 16
...count: 18
...

Use :: to reference global variable

<source lang="cpp">#include <iostream> using namespace std; int global_name = 1001; int main(void){

  int global_name = 1;  // Local variable
  cout << "Local variable value " << global_name << "\n";
  cout << "Global variable value " << ::global_name << "\n";

}</source>