Variable in C
Variable is an identifier that holds data in memory. It is used to identify input data in a program. The value of the variable can change at the time of executions. Let’s consider the syntax of a variable.
Syntax: Datatype variable_name; Syntax: Datatype variable_name1, variable_name2,variable_name3…variable nameN.We can also declare multiple variables with the same data type by using comma (,). Example:
int a, b; // a and b are variable and int is the data type. char c; // c is a variable and char is the data type.Rules for declaring the variable:
- Variable name should start with alphabets or underscore (_).
- No space is allowed in a variable while declaration.
- Variable must not be any reserved word or keyword.
Valid declaration | Invalid declaration |
int b; | int 2; |
char _name; | int a b; |
int a4; | int double; |
Types of variables in C.
There are various types of variable in C:
- local variable
- global variable
- static variable
- automatic variable
- external variable
void function1() { float x= 34.9; // Here x is local variable. }2. Global variable A global variable is declared outside of the function or block. The value of the global variable can be changed.
char name=”ABC”; // global variable void function1() { int x=10; // local variable }3. Static variable A static variable is declared with the static keyword. It contains its value during the function call. Example:
void function1(){ int x=5;//local variable will print the same value. static int y=5; //static variable will print the incremented value like: 5,6,7,...N x=x+1; y=y+1; printf("%d,%d",x,y); }4. Automatic variable An automatic variable is declared inside the block. The auto keyword is used to declare the automatic variables.
void main() { int a=5;// Here a is local variable or also automatic variable. auto int b=10;//automatic variable }5. External variable An external variable is used to share the multiple C source files by using external variables // save it as abc.h
extern int x=5; //external variable (also global)//save as prog1.c
#include "myfile.h" #include <stdio.h> void printValue() { printf("Global variable: %d", global_variable); }