AnyCompiler

const aur static

static, ek local variable par istemal hone par, matlab hai ke wo sirf ek baar initialize hota hai aur calls ke beech apni value rakhta hai — ek normal local variable ke bar'aks, 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;
}
Output
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 bar'aks, compiler waqai ise enforce karta hai. Ye waqai 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;
}
Output
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 istemal karta hai.

Practice exercise

Ek function increment() likhein jiska ek static int count ho jo 0 se shuru ho aur usmein 1 add kar ke use print kare. increment() ko teen baar call karein.