C - Data Type Constants

Introduction

There are a couple of ways in which you can define constant value.

The first is to define Pi as a symbol that's to be replaced in the program by its value during compilation.

In this case, Pi isn't a variable at all, but more a sort of alias for the value it represents.

Demo

#include <stdio.h>
#define PI   3.14159f                       // Definition of the symbol PI

int main(void)
{
      float radius = 0.0f;
      float diameter = 0.0f;
      float circumference = 0.0f;
      float area = 0.0f;

      printf("Input the diameter of a table:");
      scanf("%f", &diameter);

      radius = diameter/2.0f;/*  ww w. j av a  2 s  .  com*/
      circumference = 2.0f*PI*radius;
      area = PI*radius*radius;

      printf("\nThe circumference is %.2f. ", circumference);
      printf("\nThe area is %.2f.\n", area);
      return 0;
}

Result

how It Works

The following preprocessing directive creates a symbol.

#define PI   3.14159f                       // Definition of the symbol PI

This defines PI as a symbol that is to be replaced by the string 3.14159f.

The second option is to define Pi as a constant variable by prefixing the type name with the keyword const. For example:

const float Pi = 3.14159f;                  // Defines the value of Pi as fixed

The code above defines it as a constant numerical value with a specified type.

Demo

#include <stdio.h>

int main(void)
{
  float diameter = 0.0f;                    // The diameter of a table
  float radius = 0.0f;                      // The radius of a table
  const float Pi = 3.14159f;                // Defines the value of Pi as fixed

  printf("Input the diameter of the table:");
  scanf("%f", &diameter);

  radius = diameter/2.0f;/*ww w . j ava 2 s.c o m*/

  printf("\nThe circumference is %.2f.", 2.0f*Pi*radius);
  printf("\nThe area is %.2f.\n", Pi*radius*radius);
  return 0;
}

Result