{ A destination to learn coding }

Types of Variables

There are 3 types of variables

  1. Local Variables
  2. Global Variables
  3. Formal Parameters


Local Variables

Local variables are declared within the code blocks(i.e between the curly brackets).

Code
#include<stdio.h> // This is a comment
void func1(); //Function is declared
void func2(); //Function is declared
int main() //main function
{
  func1(); //function is called
  func2(); //function is called
  return 0;
}

func1() //function definition
{
int x=20; //variable x is declared
printf("%d",x);
}
 
func2() //function definition
{
int x=60; //variable x is declared
printf("%d",x);
}
		
Output: 2060

Above code is given for you to understand how the local variables work.
In the above code there are three functions altogether distinguished by the curly brackets.

What the code says?

In func1() variable x is assigned the value 20 and the value is printed.
In func2() variable x is assigned the value 60 and the value is printed.

The output shows that although the variable names are same in both the functions, the variables are not same. They are different variables altogether having different values.
Local variables are declared within the curly brackets and they serve within and only in that code block.

In the above given code a local variable x is created upon entry into func1() and destroyed upon its exit.
x has no value outside that code block and has no relation with the x in func2().

Note: A local variable is the one which is declared within a function of a code block.
Note: It doesn't serve outside that block.

Global Variables

Global Variables are declared outside of any code blocks or functions. They are known throughout the program and can be used by any blocks of code.

Code
#include<stdio.h>
int a=100;

void add();

int main()
{
printf("The value of global variable is %d\n",a);
add();
return 0;
}

void add()
{
int sum,b=30;
sum=a+b;
printf("The sum is %d",sum);
}


		

In the above code a variable a is declared globally (outside of any function)
This variable can be used in by functions throughout the program.
Global variables comes into use when you want to use some constant value throughout the program.

Formal Parameters

This will be taught in the later chapter

C Codes