Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Different ways to declare variable as constant in C and C++
In C programming, constants are fixed values that cannot be changed during program execution. There are multiple ways to declare variables as constants, each with its own characteristics and use cases.
Syntax
const data_type variable_name = value;
#define MACRO_NAME value
enum { constant1, constant2, ... };
Method 1: Using const Keyword
The const keyword is the most common way to create read-only variables. Once declared, attempting to modify the value results in a compilation error −
#include <stdio.h>
int main() {
const int value = 5;
printf("Value of constant variable is: %d\n", value);
/* Uncommenting the next line will cause compilation error */
/* value = 8; */
return 0;
}
Value of constant variable is: 5
Method 2: Using Enum
Enumerations create a set of named integer constants. By default, enum values start from 0 and increment by 1 −
#include <stdio.h>
enum months {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
int main() {
printf("Month values: ");
for (int i = Jan; i <= Dec; i++) {
printf("%d ", i);
}
printf("\nJanuary = %d, December = %d\n", Jan, Dec);
return 0;
}
Month values: 0 1 2 3 4 5 6 7 8 9 10 11 January = 0, December = 11
Method 3: Using Macros
Macros are preprocessor directives defined using #define. The preprocessor replaces macro names with their values before compilation −
#include <stdio.h>
#define PI 3.14159
#define MAX_SIZE 100
int main() {
printf("Value of PI: %.5f\n", PI);
printf("Maximum size: %d\n", MAX_SIZE);
double area = PI * 5 * 5;
printf("Area of circle with radius 5: %.2f\n", area);
return 0;
}
Value of PI: 3.14159 Maximum size: 100 Area of circle with radius 5: 78.54
Comparison
| Method | Type Safety | Scope | Memory |
|---|---|---|---|
| const keyword | Yes | Block/Function | Allocates memory |
| enum | Integer only | Global/Local | No memory for constants |
| Macros | No | Global | No memory allocation |
Conclusion
Choose const for type-safe variables, enum for related integer constants, and #define for simple value substitutions. The const keyword is generally preferred for modern C programming due to its type safety and scope control.
