C - Using Local variables in functions

Introduction

Functions that use variables must declare those variables.

Variables declared and used within a function are local to that function.

Consider the following code.

Both the main() and myFunction() functions declare an int variable a.

The variable is assigned the value 365 in main().

In the myFunction() function, variable a is assigned the value -10.

The same variable name is used in both functions, it holds a different value.

C variables are local to their functions.

Demo

#include <stdio.h> 

void myFunction(void); 

int main() /*from ww  w.  ja va2 s .  co m*/
{ 
   int a; 

   a = 365; 
   printf("In the main function, a=%d\n",a); 
   myFunction(); 
   printf("In the main function, a=%d\n",a); 
   return(0); 
} 

void myFunction(void) 
{ 
   int a; 

   a = -10; 
   printf("In the myFunction function, a=%d\n",a); 
}

Result

Related Topic