๐ C Constants – Fixed Values in C Programming
In C, constants are fixed values that do not change during the execution of a program. They help keep your code secure and prevent accidental modification of important values.
๐น Types of Constants
- Literal Constants โ Direct values like
100,'A',3.14 - Symbolic Constants โ Defined using
#define - Constant Variables โ Declared using
constkeyword
๐ Example: Using const Keyword
This example shows how to declare a constant using the const keyword.
#include <stdio.h>
int main() {
const float PI = 3.14159;
printf("Value of PI: %.5f\n", PI);
// PI = 3.14; // โ This will cause an error because PI is constant
return 0;
}
๐ Example: Using #define Macro
This example uses a macro to define a symbolic constant.
#include <stdio.h>
#define MAX_USERS 100
int main() {
printf("The system can support up to %d users.\n", MAX_USERS);
return 0;
}
๐ฏ Const vs #define
| Feature | const |
#define |
|---|---|---|
| Type Checking | โ๏ธ Yes | โ No |
| Memory Allocation | โ๏ธ Allocates memory | โ No memory allocation |
| Scope | Follows variable scope | Global |
๐ง Quick Tips
- Use
constwhen you need type safety. - Use
#definefor global constants or preprocessor configs.
๐ Practice Task
Try creating constants for gravity (9.8), speed of light, and your lucky number. Print them in a program!