What is Constants in C?
In C programming, a constant is a value that remains constant during program execution and cannot be changed or changed. Constants are used to represent values ​​such as numbers, characters, or strings that do not change at runtime.
Constants play an important role in writing precise and accurate code by giving meaningful names to constant values. They increase the readability, security and stability of the code. Constants are often mathematical constants (such as pi), conditional numbers, default settings, etc. It is used when the value must remain the same throughout the program.
There can be many types of constants in C
- Integer Constants:
Integer constants represent whole numbers without any fractional part.
Syntax
int age = 25; // Integer constant representing the age
- Floating-Point Constants:
Floating-point constants represent numbers with a fractional part.
Syntax
float pi = 3.14; // Floating-point constant representing the value of pi
- Character Constants:
Character constants represent individual characters enclosed within single quotes.
Syntax
char grade = ‘A’; // Character constant representing the grade
- String Constants:
String constants represent sequences of characters enclosed within double quotes.
Syntax
char message[] = “programmercoding.com”; // String constant representing a message
- Enumeration Constants:
Enumeration constants are symbolic names assigned to integral values defined in enumeration types.
Syntax
enum Color {RED, GREEN, BLUE};
- Macro Constants:
Macro constants are defined using the #define preprocessor directive and can represent any value or expression.
Syntax
#define PI 3.14
Advantages and Disadvantages of Constants in C
Example
#include <stdio.h>
#define PI 3.14
enum Weekday {MON, TUE, WED, THU, FRI, SAT, SUN};
int main() {
int radius = 5;
float area = PI * radius * radius;
printf(“Area of a circle with radius %d is %.2f\n”, radius, area);
enum Weekday today = TUE;
printf(“Today is “);
switch (today) {
case MON: printf(“Monday\n”); break;
case TUE: printf(“Tuesday\n”); break;
case WED: printf(“Wednesday\n”); break;
case THU: printf(“Thursday\n”); break;
case FRI: printf(“Friday\n”); break;
case SAT: printf(“Saturday\n”); break;
case SUN: printf(“Sunday\n”); break;
}
return 0;
}
Output
Area of a circle with radius 5 is 78.50
Today is Tuesday