Variables in C
Variables in C
Example:
int name;
int num=30;
1. int age;
2. float salary_1;
3. char _status;
4. double average_score;
5. int studentCount;
Invalid examples of variable names:
6. int 1stNumber; // Starts with a digit
7. float my-salary; // Contains a hyphen (-)
8. char int; // Same as a C keyword
9. int double; // Same as a C keyword
(assignment/increment/decrement)*/
1. Variable Declaration :
The process of telling the compiler about a variable's existence and data type is known as variable
declaration.
It notifies the compiler that a variable with a specific name and data type will be used in the program.
Still, no memory for the variable is allocated at this moment. It is usually seen at the start of a function or
block before the variable is utilized.
2. Variable Definition:
The process of reserving memory space for the variable to keep its contents during program execution is
known as a variable definition.
It is based on the data type and connects the variable name with a particular memory address of sufficient
size.
A variable in C can be declared and defined in the same statement, although they can also be separated if
necessary. Example : int x=20; //defining(Assigning) a value to the variable
During program execution the DATA/VALUE of a particular variable may change when applied to the
Loop/ Formula.
This change is possible only if the variable is Initiated(assigned) for the Loop/formula OR
printf(“%d”,x); // output:: 21
Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
1: Local Variable
A variable that is Declared and Initialized inside the function or block is called a local variable.
3:Static Variable
A variable that is declared with the static keyword is called static variable.
If you call this function many times, the local variable will print the same value for each function call,
e.g, 11,11,11 and so on.
But the static variable will print the incremented value in each function call, e.g. 11, 12, 13 and so on.
5: External Variable
We can share a variable in multiple C source files by using an external variable.
Example :
FILE_NAME :: Myfile.h
FILE_NAME :: program1.c
#include "myfile.h"
#include <stdio.h> //program_2
void printValue()
{
printf("Global variable: %d", global_variable);
}