Introduction
Constants in C are fixed values that cannot be modified during program execution. They provide a way to define unchanging values that can be used throughout the program, making code more readable, maintainable, and less prone to errors. Constants help in avoiding magic numbers and provide meaningful names to fixed values.
Key Concepts
Literal Constants: Fixed values written directly in code Symbolic Constants: Named constants defined using preprocessor or const keyword Const Keyword: Creates read-only variables Enumeration Constants: Named integer constants String Literals: Constant character sequences Immutability: Property of not being changeable
Types of Constants
1. Integer Constants
#include <stdio.h>
int main() {
// Decimal constants
int decimal = 123;
int negative = -456;
// Octal constants (prefix with 0)
int octal = 0123; // Decimal equivalent: 83
int octal2 = 0777; // Decimal equivalent: 511
// Hexadecimal constants (prefix with 0x or 0X)
int hex = 0x123; // Decimal equivalent: 291
int hex2 = 0XFF; // Decimal equivalent: 255
int hex3 = 0xABCD; // Decimal equivalent: 43981
printf("Decimal: %d\n", decimal);
printf("Octal 0123 = %d in decimal\n", octal);
printf("Hex 0x123 = %d in decimal\n", hex);
printf("Hex 0xFF = %d in decimal\n", hex2);
return 0;
}
2. Floating-Point Constants
#include <stdio.h>
int main() {
// Standard decimal notation
float simple = 3.14159;
double precise = 2.718281828;
// Scientific notation
float scientific1 = 1.23e4; // 1.23 × 10^4 = 12300
float scientific2 = 2.5e-3; // 2.5 × 10^-3 = 0.0025
double large = 6.022E23; // Avogadro's number
// Long double
long double extended = 3.141592653589793238L;
printf("Simple float: %.5f\n", simple);
printf("Scientific 1.23e4: %.2f\n", scientific1);
printf("Scientific 2.5e-3: %.6f\n", scientific2);
printf("Large number: %.3E\n", large);
printf("Extended precision: %.15Lf\n", extended);
return 0;
}
3. Character Constants
#include <stdio.h>
int main() {
// Regular character constants
char letter = 'A';
char digit = '5';
char symbol = '@';
// Escape sequence constants
char newline = '\n';
char tab = '\t';
char backslash = '\\';
char quote = '\'';
char null_char = '\0';
// Octal character constants
char octal_char = '\101'; // 'A' in octal
// Hexadecimal character constants
char hex_char = '\x41'; // 'A' in hexadecimal
printf("Letter: %c (ASCII: %d)\n", letter, letter);
printf("Digit: %c (ASCII: %d)\n", digit, digit);
printf("Octal \\101: %c\n", octal_char);
printf("Hex \\x41: %c\n", hex_char);
printf("Tab between words:\tHello\tWorld\n");
return 0;
}
4. String Constants
#include <stdio.h>
int main() {
// String literals
char *greeting = "Hello, World!";
char *empty_string = "";
char *multiline = "This is a long string that "
"spans multiple lines using "
"string concatenation.";
// String with escape sequences
char *formatted = "Line 1\nLine 2\tTabbed\n\"Quoted text\"";
// Character array initialization
char message[] = "Welcome to C programming!";
printf("Greeting: %s\n", greeting);
printf("Empty string length: %zu\n", strlen(""));
printf("Multiline: %s\n", multiline);
printf("Formatted string:\n%s\n", formatted);
printf("Message array: %s\n", message);
return 0;
}
Symbolic Constants
1. Using #define Preprocessor
#include <stdio.h>
// Macro constants
#define PI 3.14159265
#define MAX_SIZE 100
#define COMPANY_NAME "TechCorp"
#define VERSION_MAJOR 2
#define VERSION_MINOR 1
// Function-like macros
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define CIRCLE_AREA(r) (PI * SQUARE(r))
int main() {
float radius = 5.0;
int array[MAX_SIZE];
printf("Company: %s\n", COMPANY_NAME);
printf("Version: %d.%d\n", VERSION_MAJOR, VERSION_MINOR);
printf("PI value: %.8f\n", PI);
printf("Array size: %d\n", MAX_SIZE);
printf("Circle area (radius %.1f): %.2f\n",
radius, CIRCLE_AREA(radius));
printf("Square of 7: %d\n", SQUARE(7));
printf("Maximum of 15 and 23: %d\n", MAX(15, 23));
return 0;
}
2. Using const Keyword
#include <stdio.h>
int main() {
// const variables
const int MAX_STUDENTS = 50;
const float GRAVITY = 9.81;
const char GRADE_A = 'A';
const char *UNIVERSITY = "State University";
// const array
const int FIBONACCI[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34};
const int FIB_SIZE = sizeof(FIBONACCI) / sizeof(FIBONACCI[0]);
printf("Maximum students: %d\n", MAX_STUDENTS);
printf("Gravity constant: %.2f m/s²\n", GRAVITY);
printf("Top grade: %c\n", GRADE_A);
printf("University: %s\n", UNIVERSITY);
printf("Fibonacci sequence: ");
for (int i = 0; i < FIB_SIZE; i++) {
printf("%d ", FIBONACCI[i]);
}
printf("\n");
// MAX_STUDENTS = 60; // Error: cannot modify const variable
return 0;
}
3. Enumeration Constants
#include <stdio.h>
// Basic enumeration
enum Days {
MONDAY, // 0
TUESDAY, // 1
WEDNESDAY, // 2
THURSDAY, // 3
FRIDAY, // 4
SATURDAY, // 5
SUNDAY // 6
};
// Enumeration with custom values
enum Status {
FAILED = -1,
SUCCESS = 0,
WARNING = 1,
ERROR = 2
};
// Enumeration for colors
enum Colors {
RED = 1,
GREEN = 2,
BLUE = 4,
YELLOW = RED | GREEN, // Bitwise OR: 3
CYAN = GREEN | BLUE, // Bitwise OR: 6
MAGENTA = RED | BLUE // Bitwise OR: 5
};
int main() {
enum Days today = FRIDAY;
enum Status result = SUCCESS;
enum Colors favorite = BLUE;
printf("Today is day number: %d\n", today);
printf("Operation result: %d\n", result);
printf("Favorite color code: %d\n", favorite);
// Using enumeration in switch
switch (today) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
printf("It's a weekday!\n");
break;
case SATURDAY:
case SUNDAY:
printf("It's weekend!\n");
break;
}
return 0;
}
Advanced Constant Usage
1. Constant Pointers and Pointer to Constants
#include <stdio.h>
int main() {
int value1 = 10, value2 = 20;
// Pointer to constant (data is constant)
const int *ptr_to_const = &value1;
printf("Value through ptr_to_const: %d\n", *ptr_to_const);
// ptr_to_const can point to different variables
ptr_to_const = &value2;
printf("New value through ptr_to_const: %d\n", *ptr_to_const);
// *ptr_to_const = 30; // Error: cannot modify the value
// Constant pointer (pointer address is constant)
int *const const_ptr = &value1;
printf("Value through const_ptr: %d\n", *const_ptr);
// const_ptr can modify the value it points to
*const_ptr = 25;
printf("Modified value: %d\n", *const_ptr);
// const_ptr = &value2; // Error: cannot change pointer address
// Constant pointer to constant (both are constant)
const int *const const_ptr_const = &value2;
printf("Value through const_ptr_const: %d\n", *const_ptr_const);
// *const_ptr_const = 30; // Error: cannot modify value
// const_ptr_const = &value1; // Error: cannot change pointer
return 0;
}
2. Constants in Functions
#include <stdio.h>
// Function with const parameters
void displayArray(const int arr[], const int size) {
printf("Array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
// arr[i] = 0; // Error: cannot modify const parameter
}
printf("\n");
}
// Function returning const pointer
const char* getCompanyName(void) {
static const char company[] = "TechSolutions Inc.";
return company;
}
// Function with const local variables
void calculateCircle(const float radius) {
const float PI = 3.14159;
const float area = PI * radius * radius;
const float circumference = 2 * PI * radius;
printf("Radius: %.2f\n", radius);
printf("Area: %.2f\n", area);
printf("Circumference: %.2f\n", circumference);
// radius = 10.0; // Error: cannot modify const parameter
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int count = sizeof(numbers) / sizeof(numbers[0]);
displayArray(numbers, count);
const char *company = getCompanyName();
printf("Company: %s\n", company);
calculateCircle(7.5);
return 0;
}
3. Constants in Structures
#include <stdio.h>
// Structure with constant members
struct Configuration {
const int maxUsers;
const char *systemName;
const float version;
};
// Structure for student with const ID
struct Student {
const int studentID;
char name[50];
float marks;
};
int main() {
// Initialize structure with constants
struct Configuration config = {
.maxUsers = 1000,
.systemName = "Learning Management System",
.version = 2.1
};
printf("System Configuration:\n");
printf("Max Users: %d\n", config.maxUsers);
printf("System Name: %s\n", config.systemName);
printf("Version: %.1f\n", config.version);
// config.maxUsers = 2000; // Error: cannot modify const member
// Student with constant ID
struct Student student = {
.studentID = 12345,
.marks = 85.5
};
strcpy(student.name, "John Doe");
printf("\nStudent Information:\n");
printf("ID: %d\n", student.studentID);
printf("Name: %s\n", student.name);
printf("Marks: %.1f\n", student.marks);
// student.studentID = 54321; // Error: cannot modify const member
return 0;
}
Best Practices
- Use meaningful names for constants that describe their purpose
- Define constants at the top of files or in header files
- Use UPPERCASE for macro constants by convention
- Prefer const over #define for type safety when possible
- Group related constants using enumerations
- Avoid magic numbers by defining them as named constants
- Use const for function parameters that shouldn’t be modified
- Document complex constant calculations with comments
Common Applications
Mathematical Constants
#include <stdio.h>
#include <math.h>
#define PI 3.141592653589793
#define E 2.718281828459045
#define GOLDEN_RATIO 1.618033988749895
#define SQRT_2 1.414213562373095
int main() {
double angle = 45.0;
double radians = (angle * PI) / 180.0;
printf("Mathematical Constants:\n");
printf("PI: %.10f\n", PI);
printf("e: %.10f\n", E);
printf("Golden Ratio: %.10f\n", GOLDEN_RATIO);
printf("√2: %.10f\n", SQRT_2);
printf("\nCalculations:\n");
printf("sin(45°): %.6f\n", sin(radians));
printf("e^2: %.6f\n", exp(2.0));
return 0;
}
Summary
Constants in C provide immutable values that enhance code readability, maintainability, and reduce errors. They can be literal constants written directly in code or symbolic constants defined using #define, const keyword, or enumerations. Understanding different types of constants and their proper usage is essential for writing robust C programs. Constants help avoid magic numbers, provide meaningful names to fixed values, and enable compile-time optimizations.
Part of BCA Programming with C Course (UGCOA22J201)