Constants and Literals in C
Constants and literals represent fixed values that cannot be altered during the execution of a program. They are fundamental in defining values that remain the same throughout the program.
Key Topics
1. Defining Constants
Constants in C can be defined using the #define
preprocessor directive or the const
keyword.
Example: Using #define
#define PI 3.14159
int main() {
printf("Value of PI: %f\n", PI);
return 0;
}
Output:
Value of PI: 3.141590
Code Explanation: The #define
directive defines a constant named PI
with the value 3.14159
. This value cannot be changed during program execution.
2. Literals
Literals are fixed values assigned to variables or used directly in the code. They can be of various types, such as integer literals, floating-point literals, character literals, and string literals.
Example: Different Types of Literals
int age = 30; // Integer literal
float height = 5.9f; // Floating-point literal
char grade = 'A'; // Character literal
char name[] = "Alice"; // String literal
Code Explanation: Each variable is assigned a literal value of a specific type.
3. The const
Keyword
The const
keyword is used to define variables whose value cannot be modified after initialization.
Example: Using const
Variables
const int MAX_USERS = 100;
int main() {
printf("Max users allowed: %d\n", MAX_USERS);
// MAX_USERS = 200; // Error: assignment of read-only variable
return 0;
}
Code Explanation: The variable MAX_USERS
is declared as const
, making it read-only. Attempting to modify it will result in a compilation error.
Best Practices
- Use constants for values that should not change during program execution.
- Name constants using uppercase letters for clarity.
- Prefer
const
over#define
for type safety.
Don'ts
- Don't attempt to modify constants after they are defined.
- Don't use magic numbers; instead, define them as constants with meaningful names.
- Don't neglect the use of
const
where appropriate; it helps prevent unintended modifications.
Key Takeaways
- Constants provide a way to use fixed values in a program safely.
- Literals represent fixed values assigned directly in the code.
- The
const
keyword enforces read-only variables, enhancing code reliability.