Wednesday 4 March 2015

Variables in C


A variable has a value that can change. It is a memory location that can hold a value of a certain data type. Programmers refer to a variable by its name (identifier) so that it can be accessed during the course of the program. Programmers cannot use any of the keywords as variable names.

Declaring Variables

In order to use a variable in C, the programmer must first declare it specifying the data type. The most important restriction on using a variable in C is that they have to be declared at the beginning of the program. The syntax to declare a new variable is to first write the data type then followed by a valid variable identifier as given in the following examples:

int a;
float total;
unsigned int index_no;
short int number_of_students;

Above set of expressions declared, variables “a” as an integer, “total” as a floating point number, “index_no” as unsigned integer (since there are no negative index numbers) and “number_of_students” as a short integer.
Multiple variables belonging to the same data type can be defined as separate set of expressions or by listing variable names one after the other (should be separated by a coma sign (,)).

Consider the following example s:

int a;
int b;
float total;
float sub_total;

above variables can also be defined as:

int a,b;
float total, sub_total;

After declaring a variable it should be initialised with a suitable value. In C, an uninitialised variable can contain any garbage value therefore the programmer must make sure all the variables are initialised before using them in any of the expressions. Initialising a variable can be done while declaring it, just after declaring it or later within the code (before accessing/evaluating its value within an expression). In initialising a variable any of the following three approaches are valid:

int a;
a = 10;
or
int a=10;
or
int a;
--------
--------
a = 10;

Constants

The value of a constant cannot be changed after an initial value is assigned to it. The C language supports two types of constants; namely declared constants and defined constants. Declared constants are more common and they are defined using the keyword const. With the const prefix the programmer can declare constants with a specific data type exactly as it is done with variables. 
const float pi = 3.141;

Programmers can define their own names for constants which are used quite often in a program. Without having to refer to a variable such a constant can be defined simply by using the #define pre-processor directive. These are called defined constants. Following expression illustrates the use of the #define pre-processor directive


#define pi 3.141

No comments:

Post a Comment