Variables in C
Variables are used to store data, they are named so because their contents can change. C is strongly typed language, it simply means that once you declare a variable of certain data type then you can’t change the type of the variable later in the program.
Recall that C provides 4 fundamental types:
Before you can use a variable you must first declare it. Declaring a variable involves specifying type and name of the variable. Always remember the rules of naming a variable is same as that for naming identifiers. The type and range of values variable can take depends on the type of the variable. Here is the syntax of variable declaration.
Syntax: datatype variablename;
Let's create declare a varaible
int i; // declaring an int variable
i is declared as a variable of type
int, so it can take only integral values, you can’t use
i to store a string constant. On a 16-bit system variable
i can take values from
32767, while on a 32-bit system i can take values from
If you want you can declare multiple variables of the same type like this:
int x,y,z; // declaring three variables x,y and z of type int
z are of type
Initializing a variable
When a variable is declared it contains an undefined value also known as Garbage value. If you want you can assign some initial value to the variable using assignment operator i.e (
= ). Assigning a value to the variable is called initialization of the variable. Here are some examples of variable initialization:
int a = 12, b = 100; float f = 1.2; char ch = 'a'; double d1, d2, d3 = 1.2
Note: In the last case the only
d3 is initialized,
d2 contains a garbage value.