Constants in C Language

A constant is a value or variable that can’t be changed in the program, for example: 10, 40, ‘a’, 7.4, “c programming” etc.

Constants are treated just like regular variables except that their values cannot be modified after their definition.

If you try to change the the value of constant, it will render compile time error.

Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal.

There are two ways to define constant in C programming.

  1. const keyword
  2. #define preprocessor

const keyword

The const keyword is used to define constant in C programming.

Syntax

const <data_type> <var_name> = <value>;
  • <data_type> for example int, float etc.
  • <var_name> is a placeholder for the name of the constant.
  • <value> is a placeholder for the value that <var_name> takes.
  • const is a keyword.

Example

#include<stdio.h>    
int main(){    
    const float PI=3.14;    
    printf("The value of PI is: %f",PI);    
    return 0;  
}     

#define Preprocessor

Syntax

#define <VAR_NAME> <VALUE>
  • #define is a preprocessor directive.

Example

#include <stdio.h>

#define LENGTH 10   
#define WIDTH  5
#define NEWLINE '\n'

int main() {
   int area;  
  
   area = LENGTH * WIDTH;
   printf("value of area : %d", area);
   printf("%c", NEWLINE);

   return 0;
}
Example – #define Preprocessor output

It is a good programming practice to define constants in CAPITALS.

Literals: The values assigned to each constant variables are referred to as the literals. Generally, both terms, constants and literals are used interchangeably.

For example, “const int = 5;“, is a constant expression and the value 5 is referred to as constant integer literal. 

A constant is very similar to variables in the C programming language, but it can hold only a single variable during the execution of a program.