π 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; }
π‘ 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.