C – Local and Global Variables

Local variables:

  • A variable inside the function or block.
  • Local variable cannot access outside of that block.
int main()
{
            int a ; -> local variable
}

Local variables automatically initialize with garbage values. We cannot guess garbage value.

#include<stdio.h>
int main()
{
            int a;   
            printf(“%d \n”, a); -> Prints unknown value.
            return 0;
}

Format specifiers:

  • Formatting the result is very important before display to user.
  • We use following format specifiers to read and print different types of data values.
Data typeFormat specifier
int%d
char%c
float%f
string%s

Display information of different data types:

#include<stdio.h>
int main ()
{
            char* name = “Amar”;
            int age = 23;
            float salary = 35000;
            char gender = ‘M’;
            printf(“Name is : %s \n”, name);
            printf(“Age is : %d \n”, age);
            printf(“Salary is : %f \n”, salary);
            printf(“Gender is : %c \n”, gender);
            return 0;
}

We can access local variables only from the same function in which they have defined.

#include<stdio.h>
void test();
int main ()
{
            int a=10;
            printf(“a value in main : %d \n”, a);
            test();
            return 0;
}
void test()
{
            printf(“a value in test  :%d \n”, a); // Error :    
}

Global Variables:

  • Defining a variable outside to all functions.
  • Global variables can be accessed from all the functions.
#include<stdio.h>
void test();
int a=10;
int main (){
            printf(“a value in main : %d \n”, a);
            test();
            return 0;
}
void test(){
            printf(“a value in test  :%d \n”, a);       
}

Global variables automatically initialize with default values:

DatatypeDefault Value
int0
float0.00000
charBlank
stringNull
#include<stdio.h>
int a;
float b;
int main ()
{
            printf(“int : %d \n”, a);
            printf(“float : %f \n”, b);
            return 0;
}
Scroll to Top