Basics
Type Casting
Converting Types
💡 Type casting ek chhote gilas ka paani bade gilas mein daalna (implicit, safe) ya bade gilas ka paani zabardasti chhote mein bharna (explicit, kuch chhalak sakta hai) jaisa hai.
Implicit casting (automatic) tab hota hai jab chhota type bade type mein khud-ba-khud convert ho jaata hai — jaise int se float, koi data loss nahi hota.
Explicit casting (manual, (type)value likhkar) tab chahiye jab bade type se chhote mein convert karna ho, jaise double se int — decimal part cut ho jaata hai (round nahi hota, seedha truncate).
int a = 10;
double b = a; // implicit: 10.0
double pi = 3.14159;
int truncated = (int)pi; // explicit: 3 (decimal cut)
int x = 7, y = 2;
double result = (double)x / y; // 3.5 — cast pehle karo, warna integer division ho jaayega!🔄
Type casting ek chhote gilas ka paani bade gilas mein daalna (implicit, safe) ya bade gilas ka paani zabardasti chhote mein bharna (explicit, kuch chhalak sakta hai) jaisa hai.
1 / 2
⚡ Quick Recap
- Implicit = chhota to bada, automatic, safe
- Explicit = bada to chhota, manual (type) likhna padta hai
- Cast ka order matter karta hai division mein
Is page mein (2 subtopics)
Har integer type ki ek maximum range hoti hai — agar us range se bahar value store karne ki koshish karo, "overflow" ho jaata hai, aur value wrap around karke negative ya galat ho jaati hai (bina koi error diye!).
#include <limits.h>
int max = INT_MAX; // 2147483647
printf("%d\n", max + 1); // -2147483648 (wraps around!)Common Mistake: C integer overflow par koi warning ya error nahi deta — value silently galat ho jaati hai. Bade calculations mein hamesha check karo ki tumhara type kaafi bada hai (jaise long ya long long use karo agar zaroorat ho).
char aur int ke beech casting bahut common hai (ASCII values ke liye). float/double se int mein cast karte waqt decimal part simply hata diya jaata hai (truncate), round nahi hota.
int i = (int)65.9; // 65, na ki 66 (truncate, round nahi)
char c = (char)65; // 'A'
int fromChar = (int)'A'; // 65