Site icon TestingDocs.com

C Constants

Overview

In this tutorial, we will learn about C constants. Constants are read-only variables. The value of the constant cannot be changed in the program. C allows two ways to define the constants in the program

const keyword

The general syntax to define a constant using the const keyword is as follows:

const <data_type> <constant_name> = <read_only_Value>;

<data_type> const <constant_name> = <read_only_Value>;

Example

const int ROWS=10;

int const ROWS=10;

We can use the const keyword before or after the datatype.

#define directive

The general syntax to define using the #define directive is as follows:

#define <constant_name>  <readOnly_Value>

Example

#define COLUMNS 10

This #define directive instructs the C compiler to replace the COLUMNS with value 10. To increase code readability constant names are defined in UPPERCASE.

 

C Constant Action   Yes/ No 
 Initialize the constant with an initial value

 

 Read the constant value in the program
 Modify/Change the constant value in the program

 

Example

In this example, we will define a floating-point value as constant using the #define preprocessor directive. In the function, we will use the value to calculate the area of the circle.

#define PI 3.14159265

C Program

/**
*************************************************
 * Program Description:
 * C Constants Demo
 * Filename: constants.c
 * C Tutorials - www.TestingDocs.com
 ************************************************
 */
#include<stdio.h>
#define PI 3.14159265

/*Function declaration*/
void area(const float radius);

int main()
{
    /*local variable */
    float radius=0.0;
    printf("Enter the circle radius (cm):=  \n");
    scanf("%f",&radius);
    area(radius);  // Function Call
    return 0;
}

// Function definition
void area(const float radius)
{
    float circleArea=0.0;
    circleArea = PI*radius*radius; // use the constant value PI
    printf("Area of Circle = %f  cm^2\n",circleArea);
}

Notice that we have used the constant value on the left side of the assignment operator( = ).
The compiler replaces the PI name with the value in the #define directive.

circleArea = PI*radius*radius;

So this statement becomes:

circleArea = 3.14159265*radius*radius;

C Tutorials

C Tutorials on this website can be found at:

https://www.testingdocs.com/c-language-tutorial/

Exit mobile version