Tuesday, 16 August 2016

Variable Declaration and Initialization

Variable Declaration

  • Declaration introduces one or more variables within a program. it reserves memory for the variable.
  • A declaration statement begins with the type, followed by the name of one or more variables.

The general form is-
data_type variablename1, variablename2, variablename3, ..., variablenameN;

  • Variables are declared a three basic places.
  1. When these are declared inside a function, they are called local variables.
  2. When the variables are declared in the definition of the function parameters, these are called formal parameters.
  3. When variables are declared outside all functions, the are called global variables.
for example-

Local Variable Declaration
Formal Parameter

Global Variable Declaration

  • Variables when used in expressions are also referred to as operands.

Initialization 

When a variable is declared, the C compiler doesn't assign any value to the variable, unless it is instructed to do so. Such declaration is called a tentative declaration. When such declaration is made garbage value(a random value) is stored in the variable.

for example-
  int i;      // This declaration is tentative
  int x;
  x=i+5;

Variable is not assigned any known value and contains a garbage value. Therefore the vlaue of x is not defined. This is a bug in the program.

To prevent such pitfalls, always assign a value to the variable during the declaration of the variables. This is known as Initialization.

for example-
  int i=10;
  int x;
  x=i+5;
In  this declaration the value of x is 15.

No comments:

Post a Comment

If u need any help,