OverIQ.com

Variables in C

Last updated on July 27, 2020


Variables are used to store data, they are named so because their contents can change. C is a 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:

  1. int
  2. float
  3. double
  4. char

Declaring Variables #

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 variable i.

int i; // declaring an int variable

Here 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 -32768 to 32767, while on a 32-bit system i can take values from -2147483648 to 2147483647.

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

Here x, y, and z are of type int.

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:

1
2
3
4
int a = 12, b = 100;
float f = 1.2;
char ch = 'a';
double d1, d2, d3 = 1.2;

Note: In the last statement, only the d3 variable is initialized, d1 and d2 variables contain a garbage value.