Function variable scope in c

In c, variable declared inside a function has local scope only. It can be used inside function body and cannot be accessed outside of function body.

Same variable name can be as Global variable and function local variable, because c treats them as two different variable because of different scope. But it is a good practice to avoid same variable name to avoid confusions.

Variable inside Function

#include<stdio.h>

int add();

void main()
{
   add();
}
int add()
{
   int a = 30, b = 50;
   int c = 0;
   c =  a + b;
   printf("Addition is %d", c);
}

Explanation

  1. In function add(), variable a, b and c is declared and initialized with values.
  2. These variables are only be used inside function add().
  3. Using variables outside function body, gives error.

Function with same Global and Local variable

#include<stdio.h>

int add();
int age = 40;
void main()
{
   printf("Global age is %d\n", age);
   add();
   printf("Global age is %d\n", age);
}
int add()
{
   int age = 50;
   printf("Local age is %d\n", age);
}
Output:
Global age is 40
Local age is 50
Global age is 40