Variables in C programming language

A variable is a name that store data in memory location. Its value can be changed, and it can be reused many times.

The syntax to declare a variable -
type variable_list;

Example :
int a;
float b;
Here, a, b are variables. The int, float are the data types.

Rules for defining variables :
  • A variable may contain alphabets, digits, and underscore.
  • A variable name can begin with the alphabet, and underscore only. It can't begin with a digit.
  • C is case-sensitive. So, variable with Upper and lowercase letters are distinct.
  • No whitespace inside the name of the variable is permitted.
  • A name variable must not be any reserved word or keyword, such as int, float, etc.

Valid variable names :
int a;
int _abc;
int ac3;

Invalid variable names :
int 2;
int a b;
int long;


Types of Variables in C programming language :

1. Local Variable


2. Global Variable


1. Local Variable : A variable that is declared inside the function or block is called a local variable.

#include<stdio.h>
int main ()
{
      int a, b, c; /* local variable declaration */

      a = 10;
      b = 20;
      c = a + b;
      printf ("Sum of %d and %d is = %d\n", a, b, c);
      return 0;
}

Output :
Sum of 10 and 20 is = 30

2. Global Variables : A variable declared outside of the function or block is called Global Variable. Global variables retain their values during the program's lifespan, and can be reached through each of the program's functions.

#include <stdio.h>
int g; /* global variable declaration */

int main ()
{
      int a, b; /* local variable declaration */

      a = 50;
      b = 20;
      g = a - b;

      printf ("Subtraction of %d from %d is = %d\n", b,a, g);
      return 0;
}

Output :
Subtraction of 20 from 50 is = 30

0 Comments