Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Unit 1 — Type Conversion and Casting

Lesson 25 of 32 in the free C Language notes on Siksha Sarovar, written by Rohit Jangra.

Type Conversion and Casting in C

In C, values of one data type can be converted to another. There are two kinds of conversions: implicit (automatic) and explicit (casting).

---

Implicit Type Conversion (Promotion)

The compiler automatically converts a smaller type to a larger type to prevent data loss.

Hierarchy (low → high):

char → short → int → long → float → double → long double
int a = 5;
float b = 2.5;
float result = a + b;   /* a is promoted to float: 7.5 */

Integer promotion in expressions:

char c = 'A';   /* 65 */
int n = c + 1;  /* c promoted to int → 66 */

---

Explicit Type Conversion (Casting)

You force a conversion using the cast operator (type).

int a = 7, b = 2;
float result = (float)a / b;   /* 3.5, not 3 */

double d = 9.99;
int i = (int)d;   /* i = 9, decimal truncated */

---

Common Pitfalls

Integer division:

int a = 7, b = 2;
float result = a / b;          /* WRONG: 3.0 (integer division first) */
float correct = (float)a / b;  /* RIGHT: 3.5 */

Overflow:

int big = 1000000;
short s = (short)big;   /* overflow — undefined behaviour */

Signed/unsigned mismatch:

unsigned int u = 10;
int i = -1;
if (i < u)   /* WARNING: -1 compared as large unsigned number */
    printf("i is less");

---

Conversion Table

ExpressionResult TypeValue
5 / 2int2
5.0 / 2double2.5
(float)5 / 2float2.5
(int)3.9int3
'A' + 1int66
5 + 2.0double7.0