Variable in C

In C, Variable is a memory location with a given name, used by C program to store data of given type.

A variable data is overwritten if a new data or value is assigned. In c, variable is declared only once, and can be used anywhere in program, Redeclaration of variable gives Error.

Variable naming rule

  1. In c language a variable should start with character or underscore.
  2. It should not start with digit, special symbols or space. (Except underscore)
  3. A variable can consists of character, digit.
  4. Reserved words should not be used.
  5. In c, variable names are case sensitive.
  6. Same variable name cannot be declared more than once.

Syntax

data type variable_name = value | data (initialization);

Variable Declaration

In c, variable needs to be declared first, before its use. To declare, First data type then variable name and initialization is optional. If c variable not initialized, it holds garbage value.

data typeThe type of data a variable holds or store.
variable_nameName of the variable.
value | datavalue or data as per given data type.

Example

void main(){

int age = 20; // Initialization
char a = 'v'; // Initialization
float f = 22.5; // Initialization
int speed; // not initialized

}

Output variable value in c

#include<stdio.h>

void main(){

int age = 20;
char a = 'v';
float f = 22.5;

printf("%d", age);
printf("%c", a);
printf("%f", f);

}

Assign new value and overwrite variable value

Variable holds value, and its value is overwritten, if a new value or data is assigned to the variable in c.

#include<stdio.h>

void main(){

int age = 20;
printf("%d", age); // Value is 20
 
age = 50; // New value or data is assigned to variable age 
printf("%d", age); // Value is 50

}

In above example, variable age is initialized with value 20.

int age = 20;

Again variable age is assigned with value 50.

age = 50;

Hence, previous value 20 is overwritten with new value 50. It means whenever a new value or data is assigned to a variable previous or old value will be overwritten.