Variables & Data Types

⚙️ C Language 🟢 Lesson 2 of 20 📅 2026 Edition
Unlike Python, C requires you to explicitly state what type of data a variable will hold before you use it. This might feel restrictive at first, but it's exactly this strictness that lets C manage memory so precisely and run so fast.
1Declaring Variables
C Language ▶ Run Code
int age = 21;
float height = 5.9;
char grade = 'A';
double pi = 3.14159265;

Every variable declaration follows the pattern type name = value;. Once declared with a type, that variable can never hold a different type of data for the rest of the program — this is called static typing, the opposite of Python's dynamic typing.

2The Core Data Types

You can check how much memory any type uses with the sizeof operator: printf("%zu", sizeof(int)); typically prints 4 (bytes).

3Format Specifiers

Because printf() doesn't automatically know a variable's type, you must tell it using a format specifier that matches:

C Language ▶ Run Code
printf("Age: %d\n", age);        // %d for int
printf("Height: %f\n", height);  // %f for float/double
printf("Grade: %c\n", grade);    // %c for char
4Constants with const and #define

If a value should never change after being set, mark it as constant:

C Language ▶ Run Code
const float PI = 3.14159;
#define MAX_USERS 100

const creates a real, type-checked variable that just can't be reassigned. #define is a preprocessor macro that performs simple text substitution before compilation even begins — both are common, but const is generally considered the safer, more modern choice.

⚠️ Common Mistake: Using the Wrong Format Specifier

Writing printf("%d", height) when height is a float produces garbage output instead of an error — C trusts you completely and doesn't check that the specifier matches the actual variable type. Always double-check that %d, %f, %c, and %s match the variable they're printing.

💻 Try It Yourself

Declare an int, a float, and a char representing a product's quantity, price, and category code, then print all three with correctly matching format specifiers.

C Language ▶ Run Code
#include <stdio.h>

int main() {
    int quantity = 5;
    float price = 249.50;
    char category = 'E';

    printf("Qty: %d, Price: %.2f, Category: %c\n", quantity, price, category);
    return 0;
}
Run This in Our Compiler →