Constants refers to the fixed values that do not change during the execution of a program. A “constant” is a number, character, or character string that can be used as a value in a program. Use constants to represent floating-point, integer, enumeration, or character values that cannot be modified. C supports several types of constants. There may be a situation in programming that the value of certain variables to remain constant during execution of a program. In doing so we can use a qualifier const at the time of initialization.
For example :
1. const float pie =3.147;
2. const int radius =4;
3. const char c = 'A';
4. const char name[] = "Samina Kauser";
In C constant can also be used using preprocessor directive
For example :
define FIRST_NUMBER 1
const is a new data type qualifier in C defined by ANSI
Types of constant in C Language
Primary Constant
Primary Constant have following sub categories
- Integer Constant
- Real constant
- Character constant
Secondary Constant
Secondary Constant have following sub categories
- Array
- Pointer Structure
- Union
- Enum
Constant definitions typically follow the #include directives at the top of C source code:
#include<stdio.h>
#define SPEEDLIMIT 55
#define RATE 15
#define FIRST_TICKET 85
#define SECOND_TICKET 95
#define THIRD_TICKET 100
int main()
{
int total,fine,speeding; puts("Speeding Tickets\n");
/* first ticket */
speeding = FIRST_TICKET - SPEEDLIMIT;
fine = speeding * RATE;
total = total + fine;
printf("For going %d in a %d zone:
$%d\n",FIRST_TICKET,SPEEDLIMIT,fine);
/* second ticket */
speeding = SECOND_TICKET - SPEEDLIMIT;
fine = speeding * RATE;
total = total + fine;
printf("For going %d in a %d zone:
$%d\n",SECOND_TICKET,SPEEDLIMIT,fine);
/* third ticket */
speeding = THIRD_TICKET - SPEEDLIMIT;
fine = speeding * RATE;
total = total + fine;
printf("For going %d in a %d zone:
$%d\n",THIRD_TICKET,SPEEDLIMIT,fine);
/* Display total */
printf("\nTotal in fines: $%d\n",total);
return(0);
}