C Variable Declaration and Initialization

πŸ“Œ C Variable Declaration and Initialization

In C, before you use a variable, you must declare it. And if you want it to start with a value β€” that’s called initialization. Let’s see how both work like a charm in real C programs.

πŸ”Ή Declaration in C

When you declare a variable, you’re telling the compiler, “Hey! I’m going to use this variable.”

int age;

This creates a variable named age that can store an integer.

πŸ”Ή Initialization in C

Initialization means giving that variable a value at the time of declaration.

int age = 25;

πŸ“ Example: Declare and Initialize Variables

Let’s declare and initialize different types of variables in one go!

#include <stdio.h>

int main() {
    int age = 25;
    float weight = 72.5;
    char grade = 'A';

    printf("Age: %d\n", age);
    printf("Weight: %.2f kg\n", weight);
    printf("Grade: %c\n", grade);

    return 0;
}
  

Try It Now

πŸ’‘ Tip: Declare Before You Use

C is a strictly-typed language. That means you must declare your variables before using them β€” or the compiler will throw a tantrum (aka, error!).

πŸ”§ Multiple Declarations

You can declare multiple variables of the same type like this:

int x = 5, y = 10, z = 15;

🚫 Common Mistake

Don’t forget the semicolon ; at the end. It’s like the period at the end of a sentence in C.

🎯 Try This Challenge

Try declaring variables for your name, age, height, and initial β€” then print them using printf!

πŸ“š Summary

  • Declaration sets up a variable.
  • Initialization assigns it a starting value.
  • You can declare and initialize in one line.