Constants and Variables
In C, constants and variables are used to store data, but they have distinct characteristics and usage. Here’s a brief overview:
Constants in C
- Definition: A constant is a value that cannot be modified after it is defined.
- Types of Constants:
- Literal Constants: Directly used values, like numbers and characters
int age = 30; // 30 is a literal constant
char letter = ‘A’; // ‘A’ is a literal constant
- Defined Constants: Created using the
#define
preprocessor directive
#define PI 3.14
- Const Qualifier: Declares a variable whose value cannot be changed after initialization
const int MAX_USERS = 100;
Variables in C
- Definition: A variable is a named storage location in memory that can hold different values throughout the program’s execution.
- Declaration and Initialization:
int userCount; // Declaration
userCount = 0; // Initialization
Usage:
- Variables can be modified at any point in the program.
userCount += 1; // userCount is now 1
Key Differences
- Mutability:
- Constants cannot be changed once set.
- Variables can be reassigned throughout the program.
- Usage:
- Use constants for fixed values (like mathematical constants or configuration).
- Use variables for data that may change (like counters or user inputs).
Example Code
Here’s a simple example demonstrating both constants and variables:
#include <stdio.h>
#define PI 3.14 // Defined constant
int main() {
const int MAX_USERS = 100; // Const variable
int userCount = 0; // Variable
// Simulating user additions
for (int i = 0; i < 5; i++) {
userCount++; // Increment user count
if (userCount > MAX_USERS) {
printf(“Maximum user limit reached!\n”);
break;
}
}
printf(“Current user count: %d\n”, userCount);
printf(“Value of PI: %f\n”, PI);
return 0;
}
Summary
- Constants: Use
#define
orconst
for values that should not change. - Variables: Use standard data types (like
int
,float
) to store and modify values as needed.