const aur static
static, ek local variable par use hone par, matlab hai ki wo sirf ek baar initialize hota hai aur calls ke beech apni value rakhta hai — ek normal local variable ke ulat, jo har baar uska function chalne par scratch se recreate hota hai.
#include <stdio.h>
void increment() {
static int count = 0;
count++;
printf("%d\n", count);
}
int main() {
increment();
increment();
increment();
return 0;
}1 2 3
const: ek promise jo compiler enforce karta hai
const ek variable ko initialization ke baad unmodifiable mark karta hai — aur ek comment ya naming convention ke ulat, compiler actually ise enforce karta hai. Ye genuinely wahi hai jo gcc report karta hai — ek real run se capture kiya gaya, plausible dikhne ke liye likha nahi gaya:
#include <stdio.h>
int main() {
const int max = 100;
max = 200;
printf("%d\n", max);
return 0;
}main.c: In function ‘main’:
main.c:5:9: error: assignment of read-only variable ‘max’
5 | max = 200;
| ^Aage: C mein error handling — exceptions kyun nahi hain, aur return-code convention jo C iski jagah use karta hai.
Practice exercise
Ek function increment() likho jiska ek static int count ho jo 0 se shuru ho aur usme 1 add karke use print kare. increment() ko teen baar call karo.