C - Using global variables

Introduction

Global variables make the variable declaration universal.

Any function anywhere in the program can access the variable.

The following code shows how a global variable is declared and used.

The global variables age and float are affected by both functions.

Demo

#include <stdio.h> 

void half(void);
void twice(void);

int age;/*w w  w . j a  v a 2 s  . co  m*/
float feet;

int main()
{
  printf("How old are you: ");
  scanf("%d", &age);
  printf("How tall are you (in feet): ");
  scanf("%f", &feet);
  printf("You are %d years old and %.1f feet tall.\n",
    age, feet);
  half();
  twice();
  printf("But you're not really %d years old or %.1f feet tall.\n",age,feet); 
    return(0);
}

void half(void)
{
  float a, h;

  a = (float)age / 2.0;
  printf("Half your age is %.1f.\n", a);
  h = feet / 2.0;
  printf("Half your height is %.1f.\n", h);

}
void twice(void)
{
  age *= 2;
  printf("Twice your age is %d.\n", age);
  feet *= 2;
  printf("Twice your height is %.1f\n", feet);
}

Result

The code declares the global int variable age and the float variable feet.

These are global variables because they're declared outside of any function.

The variables are used in every function.

Their values can be accessed throughout the code. Even when those values are changed in the twice() function, the main() function uses the new values.

Related Topic