Dec 29, 2011

Constants

C allows a value in variable to be constant or in other words, a read only variable. A constant variable can be used like any other variables. To declare a constant variable, keyword const is specified during the declaration,

#include<stdio.h>

int main()
{
   const float PI = 3.1416;
   int rad = 2;
   float area = PI * rad * rad;
}

Pre-processor #define provides another method to define a constant. #define does not declares a variable but creates an identifier for 3.1416 called PI. Anywhere PI appears in the program, 3.1416 will be substituted.

#include<stdio.h>
#define PI 3.1416

int main()
{
   int rad = 2;
   float area = PI * rad * rad;
}