Constants in C Programming Language

Notes:

Constants in C Programming Language

Variable:
Variable is a named memory location, whose value can change during the execution of a program.

Constant:
Constant is a named memory location, whose value never changes during the execution of a program.

I.e. constants stay constant whereas variables vary.

Declaring and initializing constants:
In order to allocate a chunk of memory and access it within a program, we need to declare a variable or a constant. Declaring a variable or a constant: means allocating a memory location for some data

In order to change the value in a variable or constant, we need to initialize or assign a value to it.
Initializing a variable or a constant: means putting initial data value in that allocated memory location

Syntax for declaring and initializing constants:

Note:
There are 2 different ways in which we can define constants in C programming language the first way is using const keyword and other way is using #define preprocessor statement. Constants defined using #define preprocessor statement are called symbolic constants.

// declaration and initialization of a single constant
const datatype NAME_OF_CONSTANT = value;
Ex:
const float PI = 3.142;

OR

#define NAME_OF_CONSTANT value
Ex:
#define PI 3.142

Note: Constants must be initialized when they are declared.

// declaration and initialization of multiple constants
const datatype NAME_OF_CONSTANT1 =value, NAME_OF_CONSTANT2 =value,...;
Ex:
const float PI = 3.142, E = 2.71828;

OR

// we cannot declare and initialize multiple constants on a single line using #define
Ex:
#define PI 3.142
#define E 2.71828

Example Code:
#include <stdio.h>
#define PI 3.142
#define E 2.71828

int main()
{
/*
int playerScore = 0;
const float PI = 3.142;

printf("player score = %d\n",playerScore); // 0
printf("PI = %.3f\n",PI); // 3.142

playerScore = 10;
printf("player score = %d\n",playerScore); // 10

// PI = 4.142; // error

//printf("PI = %.3f\n",PI); // 3.142

const float PI=3.142, E=2.71828;
printf("PI = %.3f\n",PI); // 3.142
printf("E= %.5f\n",E); // 2.71828
*/

printf("PI = %.3f\n",PI); // 3.142
printf("E= %.5f\n",E); // 2.71828

return 0;
}