Constants

Lesson 11
Author : Afrixi
Last Updated : January, 2023
C - Programming Language
This course covers the basics of programming in C.

In C, a constant is an identifier whose value cannot be changed during the execution of the program. Constants are used to store values that are fixed and do not change, such as mathematical constants or conversion factors. Defining a value as a constant can also make the code more readable and easier to maintain.

To define a constant in C, we use the const keyword followed by the data type and the constant name, like so:

const data_type constant_name = value;

For example, to define a constant named PI with a value of 3.14159, we can write:

const double PI = 3.14159;

Once defined, we can use the constant in our code as if it were a variable, but we cannot modify its value.

Here’s an example code that uses constants to calculate the area of a circle:

#include <stdio.h>

int main() {
    const double PI = 3.14159; // defining a constant for pi

    double radius; // defining a variable for the radius of the circle
    printf("Enter the radius of the circle: ");
    scanf("%lf", &radius); // reading the radius from the user

    double area = PI * radius * radius; // calculating the area of the circle using the constant PI

    printf("The area of the circle with radius %.2f is %.2f\n", radius, area);

    return 0;
}

In this example, we define a constant named PI with a value of 3.14159. We then prompt the user to enter the radius of the circle and read the value into the variable radius. We use the constant PI to calculate the area of the circle, which is then printed to the console.