Using Constants in Your Computer Program

Using Constants in C:

The C program below finds the area of a circle. In this program the value of π is defined in two different ways. One is by using using the preprocessor directive '#define' to make 'PI' equal to 3.142857. The other uses the key work 'const' to define a double called 'pi' equal to 22.0/7.0. The difference between these two ways of defining a constant is that the '#define' directive replaces PI with example what follows it in the code prior to compiling that code, and the 'const' keyword stores a value into memory that is called by the program whenever the constant name appears.


Below the source we can see the outputs are not exactly the same. We could make them the same by replacing '#define PI 3.142857' with '#define PI 22.0/7.0. However, if this were a large program where 'PI' appeared often, we would not want to do that. This is because the '#define' directive would cause the program to calculate 22.0/7.0 everywhere 'PI' appears. In this program the constant 'pi' is assigned the value resulting from the calculation of 22.0/7.0. The math to determine this value is performed only once. On the other hand, there may be cases, such as in embedded micro-controller applications where memory is very limited. In such a case, the '#define' directive can be used to save that space in memory.


#include <stdio.h>
#include <math.h>

#define PI 3.142857
const double SQUARED = 2.0;
const double pi = 22.0 / 7.0;

int main()
    double areaOfCircle;
    double radiusOfCircle = 2.0;

    areaOfCircle = pi*pow(radiusOfCircle, SQUARED);
    printf("The area of the circle is %f\n",areaOfCircle);

    areaOfCircle = PI*pow(radiusOfCircle, SQUARED);
    printf("The area of the circle is %f\n",areaOfCircle);

    return 0;


How a constant is defined in a C program can make a different in the speed, memory footprint, and precision of the program.
Home | Products | Electronics | Programming | SpazzOuts | Contact
© Copyright 2014 - 2017 SpazzTech LLC. All Rights Reserved
Made with Adobe Muse