C - Function Global variables

Introduction

You can declare global variables to share data between functions.

The global variable are outside any functions.

The global variables are accessible anywhere.

Demo

#include <stdio.h>

int count = 0;                         // Declare a global variable

// Function prototypes
void test1(void);
void test2(void);

int main(void)
{
  int count = 0;                       // This hides the global count

  for (; count < 5; ++count)
  {/*from www  . j a  v  a 2s.  c  o m*/
    test1();
    test2();
  }
  return 0;
}

// Function test1 using the global variable
void test1(void)
{
  printf("test1   count = %d\n", ++count);
}
// Function test2 using a static variable
void test2(void)
{
  static int count;                   // This hides the global count
  printf("test2   count = %d\n", ++count);
}

Result

The global variable count is defined as follows:

int count = 0;

Because it is global it will be initialized by default to 0 if you don't initialize it.

The second variable count is an automatic variable that's declared in main():

int count = 0; // This hides the global count

Because it has the same name as the global variable, the global variable count can't be accessed from main().

The local variable count hides the global variable.

The third variable is a static variable count that's declared in the function test2():

static int count; // This hides the global count

Because this is a static variable, it will be initialized to 0 by default.

This variable hides the global variable of the same name, so only the static variable count is accessible in test2().

The function test1() is using the global count.

The functions main() and test2() use their local versions of count.

Related Topics