Variables in C Language – a variable is an identifier whose value changes from time to time during execution.
It is a named data storage location in your computer’s memory. By using a variable’s name in your program, you are, in effect, referring to the data stored there. A variable represents a single data item i.e. a numeric quantity or a character constant or a string constant.Note that a value must be assigned to the variables at some point
*Note that a value must be assigned to the variables at some point of time in the program which is termed as an assignment statement.
The variable can then be accessed later in the program. If the variable is accessed before it is assigned a value, it may give garbage value.
The data type of a variable doesn’t change whereas the value assigned to can change.
All variables have three essential attributes:
- The name
- The value
- The memory, where the value is stored.
For example, in the following C program a, b, c, d are the variables but variable e is not declared and is used before declaration. After compiling the source code and look what gives?
int a, b, c;
a = 3;
b = 5;
c = a + b;
d = ‘a’;
After compiling the code, this will generate the message that variable e not defined.
Declaring Variables in C Language
Before any data can be stored in the memory, we must assign a name to these locations of memory.
For this we make declarations. Declaration associates a group of identifiers with a specific data type.
All of them need to be declared before they appear in program statements, else accessing the variables results in junk values or a diagnostic error.
The syntax for declaring variables is as follows
data- type variable-name(s);
short int a, b;
int c, d;
long c, f;
float r1, r2;
Initializing Variables in C
When variables are declared initial, values can be assigned to them in two ways
a) Within a Type declaration
The value is assigned at the declaration time.
int a = 10;
float b = 0.4 e –5;
char c = ‘a’;
b) Using Assignment statement
The values are assigned just after the declarations are made.
a = 10;
b = 0.4 e –5;
c = ‘a’;