Variables
To create a variable, you must specify its data type and a name. This process is called declaration.
Initialization: Assigning a value at the time of declaration.
Naming Rules: Must start with a letter or underscore, cannot be a keyword (like
int), and are case-sensitive (ageandAgeare different).
#include <stdio.h>
int main() {
int score; // Declaration
score = 10; // Assignment
int level = 1; // Declaration + Initialization
printf("Initial Score: %d\n", score);
score = 20; // Value changed (Variable)
printf("Updated Score: %d\n", score);
return 0;
}Expected Output:
Initial Score: 10
Updated Score: 202. Constants (const and #define)
There are two primary ways to define constants in C. Using constants makes your code "cleaner" because you avoid "magic numbers" (random numbers in your code whose purpose isn't clear).
A. The const Keyword
This creates a variable that is read-only.
B. The #define Preprocessor
This replaces every instance of a name with a value before the program even starts compiling. It does not occupy memory like a variable does.
#include <stdio.h>
// Method 1: Preprocessor constant (No semicolon at the end!)
#define PI 3.14159
int main() {
// Method 2: The const keyword
const int MAX_USERS = 100;
printf("Value of PI: %.5f\n", PI);
printf("Max Users allowed: %d\n", MAX_USERS);
// MAX_USERS = 200; // This would cause a COMPILE ERROR
return 0;
}Expected Output:
Value of PI: 3.14159
Max Users allowed: 100