C Tutorial/Language/Global variables

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

Declare global variables

A global variable is available to all functions in your program.

A local variable is available only to the function in which it"s created.

  1. Global variables are declared outside of any function.
  2. Global variables are typically declared right before the main() function.
  3. You can also declare a group of global variables at one time:


<source lang="cpp">int s,t;</source>

Define and use Global variables

<source lang="cpp">#include <stdio.h> int count = 0; /* Declare a global variable */ void test1(void){

 printf("\ntest1   count = %d ", ++count);

} void test2(void){

 static int count;                   /* This hides the global count */
 printf("\ntest2   count = %d ", ++count);

}

int main(void){

 int count = 0;                      /* This hides the global count */
 for( ; count < 5; count++) {
   test1();
   test2();
 }
 return 0;

}</source>

value of i in main 0
     value of i after call 50