Variables in C Language

variable is a name of the memory location. It is used to store data. C variable might be belonging to any of the data type like int, float, char etc.

Variables value can be changed and it can be reused many times.

Upper and lowercase letters are distinct because C is case-sensitive.

Syntax

type variable_list;  

Example

int a;  
float b;  
char c; 
//Here, a, b, c are variables. The int, float, char are the data types.

//We can also provide values while declaring the variables as given below:

int a=10,b=20;//declaring 2 variable of integer type  
float f=20.8;  
char c='A';  

Rules for defining variables

  • A variable name can start with the alphabet, and underscore only. It can’t start with a digit.
  • A variable name can have alphabets, digits, and underscore.
  • No special symbols are allowed other than underscore.
  • No whitespace is allowed within the variable name.
  • Variable are case sensitive for example Anil and anil are different.
  • A variable name must not be any reserved word or keyword, e.g. int, float, char, etc.

You should always try to give meaningful names to variables. For example: firstName is a better variable name than fn.

C is a strongly typed language. This means that the variable type cannot be changed once it is declared. 

To indicate the storage area, each variable should be given a unique name (identifier).

Valid variable names

int a;  
int _ab;  
int a30; 

Invalid variable names

int 2;  
int a b;  
int long;  

Variable initialization

Variable initialization means assigning a value to the variable.

Variables can be initialized (assigned an initial value) in their declaration.

data_type variable_name = value;

Example

int x = 50, y = 30; char flag = ‘x’, ch=’l’;
int d = 3, f = 5;           // definition and initializing d and f. 
byte z = 22;                // definition and initializes z. 
char x = 'x';               // the variable x has the value 'x'.

Example

#include <stdio.h>

int main () {

   /* variable definition: */
   int a, b;
   int c;
   float f;
 
   /* actual initialization */
   a = 100;
   b = 200;
  
   c = a + b;
   printf("value of c : %d \n", c);

   f = 70.0/3.0;
   printf("value of f : %f \n", f);
 
   return 0;
}
C Variable Example Output