What are variables in C?
The variable is the basic unit of storage that holds the value while the program is executed. We can also say that it is a name given to the memory location. A variable is defined by data-types provided by C.
It may belong to any data-types in C that can be char, int, float, double, and void.
Rules for naming C Variables:
- A variable name must begin with a letter or underscore.
- They are case sensitive that is Score and score are not the same.
- They can be constructed with digits, letters and underscore.
- No special symbols are allowed other than underscores.
- A variable name cannot be a keyword. Example,
int
cannot be a variable name as it is an in-built keyword.
Variable Definition, Declaration, and Initialization in C
Defining a variable:
Defining a variable means the compiler has to now assign storage to the variable because it will be used in the program. It is not necessary to declare a variable using an extern keyword, if you want to use it in your program. You can directly define a variable inside the main() function and use it.
To define a function we must provide the data type and the variable name. We can even define multiple variables of the same data type in a single line by using a comma to separate them.
type variable_list_name
, where type must be the valid C data-type.
Example:
1 2 3 4 | int i, j, k; char c, ch; float f, amount, salary; double db; |
Declaration of Variables:
The declaring variable is useful for multiple files and the variable is declared in one of the files and is used during linking the file.
Declaration of variables must be done before they are used in the program. Declaration does the following things.
- It tells the compiler what the variable name is.
- It specifies what type of data the variable will hold.
A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program.
The user needs to use the keyword extern to declare a variable at any place. Though you can declare variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.
1 2 3 | extern int a; extern float b; extern double c,d; |
Initialization of Variables:
initialization is simply giving the variable a certain initial value which may be changed during the program.
A variable can be initialized and defined in a single statement, like:
1 | int a = 20; |
Let see an example for declaring, defining and initializing in C:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <stdio.h> // Variable declaration: extern int x, y; extern int z; extern float f; int main () { /* variable definition */ int x, y; int z; float f; /* actual initialization */ x = 30; y = 20; z = x + y; printf("value of z: %d \n", z); f = 70.0/3.0; printf("value of f: %f \n", f); return 0; } |
The output:
1 2 | value of z : 30 value of z : 23.333334 |