Skip to main content

Variables in C

A variable is a named container that occupies a memory location to store a value. That value can be read and changed during program execution.

Declaration and Initialization

Declaration — reserves memory for the variable:
int number;
Initialization — declaration + assigning a value:
int number = 10;
Syntax:
data_type variable_name;
data_type variable_name = value;

Naming Conventions

StyleExampleUsed In
Pascal CaseUserNameTypes, structs
Camel CaseuserNameVariables, functions
Snake Caseuser_nameC variables, Python
Kebab Caseuser-nameNot valid in C

Variable Classification by Data Type

Data TypeKeywordSizeRange
Characterchar1 byte−128 to 127
Integerint4 bytes±2.1 billion
Short Integershort2 bytes−32,768 to 32,767
Long Integerlong4–8 bytesPlatform dependent
Floatfloat4 bytes±3.4 × 10³⁸
Doubledouble8 bytes±1.7 × 10³⁰⁸
Long Doublelong double10–16 bytesEven higher

Variable Classification by Scope

TypeDeclared InScopeLifetime
LocalA function/blockThat block onlyUntil block ends
GlobalOutside functionsWhole fileWhole program
StaticWith staticLimited, keeps valueUntil program ends
ExternAnother fileGlobalDepends on origin
RegisterWith registerCPU registerUntil block ends

Format Specifiers

Used with printf() and scanf() to read/print specific types:
SpecifierData TypeExample Output
%dint25
%ffloat5.68
%lfdouble3.14
%ccharA
%sstringHello
printf("%d", 25);       // 25
printf("%.2f", 5.6789); // 5.68
printf("%.2lf", 3.14);  // 3.14
printf("%c", 'A');      // A
printf("%s", "Hello");  // Hello

Example

#include <stdio.h>

int main() {
    int age = 20;
    float cgpa = 8.75;
    char grade = 'A';

    printf("Age  : %d\n", age);
    printf("CGPA : %.2f\n", cgpa);
    printf("Grade: %c\n", grade);

    return 0;
}