Constants in C

Constants in C. Constants in C Tutorial. Learn Constants in C.
Constants in C

What are Constants in C?

In C, constants are values that are fixed and cannot be changed during the execution of the program. Constants are used to represent values that are known at compile time, such as the value of pi, the number of days in a week, or the maximum value of a data type.

Here’s a list of some of the most commonly used constants in C:

SR. NO.ConstantsDescriptionExample
1NULLA pointer to a null objectint* ptr = NULL;
2EOFEnd of file markerwhile ((ch = getchar()) != EOF)
3TRUEBoolean true valueif (flag == TRUE)
4FALSEBoolean false valueif (flag == FALSE)
5INT_MAXThe maximum value of an ‘int’int i = INT_MAX;
6INT_MINThe minimum value of an ‘int’int i = INT_MIN;
7LONG_MAXThe maximum value of an ‘long’long l = LONG_MAX;
8LONG_MINThe minimum value of an ‘long’long l = LONG_MIN;
9FLT_MAXThe maximum value of an ‘float’float f = FLT_MAX;
10FLT_MINThe minimum value of an ‘float’float f = FLT_MIN;
11DBL_MAXThe maximum value of an ‘double’double d = DBL_MAX;
12DBL_MINThe minimum value of an ‘double’double d = DBL_MIN;

Different ways to define Constants in C:

1. Using #define preprocessor directive:

#define PI 3.14159265358979323846

2. Using const keyword:

const int MAX_VALUE = 100;

3. Using enum keyword:

enum boolean { FALSE, TRUE };

Example:

Here’s an example program that demonstrates the use of constants in C:

#include <stdio.h>

#define PI 3.14159265358979323846
const int MAX_VALUE = 100;
enum boolean { FALSE, TRUE };

int main() {
    printf("The value of PI is: %lf\n", PI);
    printf("The maximum value is: %d\n", MAX_VALUE);
    printf("The value of TRUE is: %d\n", TRUE);
    return 0;
}

Output:

The value of PI is: 3.141593
The maximum value is: 100
The value of TRUE is: 1

Rules to follow while using Constants in C:

  1. Constants cannot be modified once they are defined.
  2. Constants must be initialized at the time of declaration.
  3. Constants have a scope that is limited to the block in which they are defined.
  4. Constants should be named using uppercase letters to differentiate them from variables.

More: