This website completely moved to new platform. For latest content, visit

Search this Site

1 Oct 2013

constants in C

In this article we will see a small example of using constants in c. constants are declared with a keyword const.

 const float PI = 3.14 ;  //constant of type float
 const char myStr[] = " *** *** " ;  //constant of char array 

The program below is to find the area and perimeter of circle in which we use const . 
In the program below we have declared PI as a constant which value is given as 3.14 
It means PI value cannot be changed either at compile time or run-time . if we try to change the value of a constant variable it gives a compile-time error.

Any Integral or char/string variables can be declared as constants. 

int main()
 const float PI = 3.14 ;
        const char myStr[] = "*** ***" ;
 int r=0;
 float area;
 float perimeter;
    printf("%s \n",myStr);
    printf(">>> c Program to find Area and Perimeter of Circle <<<");
    printf("\nEnter radius value: ");
    scanf("%d",&r); //taking radius as input
    area = PI * r * r; //getting area of circle
    printf("\nArea of circle is: %f" , area);
  //if we try to assign a value to PI or myStr , we get compile-time error
     //PI = 123;

     perimeter = 2 * PI * r; //getting perimeter of circle
     printf("\nPerimeter of circle: %f" , perimeter);

Sample Output :