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
Declare variable as constant in C
In C programming, variables can be declared as constants using the const keyword or the #define preprocessor directive. Constants ensure that variable values cannot be modified after initialization, providing data integrity and preventing accidental changes.
Syntax
const datatype variable_name = value; #define CONSTANT_NAME value
Method 1: Using const Keyword
Variables can be declared as constants by using the const keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of uninitialized constant variables is zero.
#include <stdio.h>
int main() {
const int a;
const int b = 12;
const float pi = 3.14159;
printf("The default value of variable a: %d<br>", a);
printf("The value of variable b: %d<br>", b);
printf("The value of pi: %.2f<br>", pi);
return 0;
}
The default value of variable a: 0 The value of variable b: 12 The value of pi: 3.14
Method 2: Using #define Preprocessor Directive
Variables can be declared as constants by using the #define preprocessor directive. It creates a symbolic constant by replacing all occurrences of the defined name with its value during preprocessing.
#include <stdio.h>
#define NUM 25
#define PI 3.14159
#define MESSAGE "Hello World"
int main() {
printf("The value of NUM is: %d<br>", NUM);
printf("The value of PI is: %.2f<br>", PI);
printf("Message: %s<br>", MESSAGE);
return 0;
}
The value of NUM is: 25 The value of PI is: 3.14 Message: Hello World
Comparison
| Feature | const Keyword | #define Directive |
|---|---|---|
| Memory allocation | Allocates memory | No memory allocation |
| Type checking | Type-safe | No type checking |
| Scope | Follows block scope | Global scope |
| Debugging | Available in debugger | Not available in debugger |
Key Points
- Use
constfor type-safe constants with proper scope rules. - Use
#definefor simple symbolic replacements and global constants. - Constants declared with
constcannot be modified after initialization. - The
#definedirective is processed during preprocessing, not compilation.
Conclusion
Both const and #define serve to create constants in C, but const provides type safety and follows scope rules, while #define offers simple text replacement. Choose based on your specific requirements for type checking and scope control.
