View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Type Casting in C: Implicit and Explicit Conversions Explained

Updated on 04/06/20254,322 Views

Why does dividing two integers in C sometimes return a float—and sometimes not?

The answer lies in type casting in C.

Type casting in C means converting one data type into another. It helps you control how data is handled during operations—like turning an int into a float to get precise results. C supports two types of type casting: implicit, which is done automatically by the compiler, and explicit, where the programmer manually casts the value.

In this tutorial, you’ll learn how type casting in C works, when to use it, and how to avoid unexpected results. We’ll explain the difference between implicit and explicit type casting with simple examples, show how to use casting in arithmetic operations, and highlight common mistakes.

By the end, you’ll write safer and more accurate C programs using proper type conversions. Want to master these C fundamentals with real-time projects? Join our Software Engineering Courses and take your programming skills to the next level.

What is Type Casting in C?

Type casting in C refers to the process of converting a variable from one data type to another. It allows you to change the type of a variable or value to suit a specific operation or function requirement.

This is essential when you need to perform operations involving different data types, or when you want to ensure data is stored in the correct type for specific tasks.

The general syntax for explicit type casting in C is:

(new_data_type) variable;

Where:

  • new_data_type is the type you want to convert the variable into.
  • variable is the original value or variable that you want to cast.

Let’s dive into a simple type casting in C with examples to understand the syntax and its practical use.

In this example, we’ll manually convert a float value to an int using explicit type casting.

#include <stdio.h>
int main() {
    float num = 9.75;     // floating point number
    int result = (int) num;  // Explicit casting: float to int
    printf("Converted value: %d\n", result);
    return 0;
}

Output:

Converted value: 9

Explanation:

  • (int) num: This is the explicit type casting syntax that tells the compiler to convert the float value 9.75 into an int.
  • Since int cannot hold decimal values, the value is truncated (not rounded), and only the integer part 9 is stored in the result variable.

Ready to move beyond C programming and unlock new career opportunities? We've curated these forward-looking courses specifically to enhance your professional growth:

Also Read: Compiler vs Interpreter: Difference Between Compiler and Interpreter

Now that you understand the basic syntax of type casting, let's explore the different types of type casting in C and when to use each one.

Types of Type Casting in C

Type casting in C can be broadly categorized into two types: Implicit Type Casting (Automatic Type Casting) and Explicit Type Casting (Manual Type Casting).

Let's dive into each type, and look at examples to understand when and how to use them.

Implicit Type Casting (Automatic Type Casting)

Implicit Type Casting happens automatically when you assign a value of a smaller data type to a larger data type. The C compiler performs this conversion without requiring any explicit instruction from the programmer. This type of casting is safe, as the smaller data type’s value can fit into the larger data type without loss of information.

For example, when calculating the average of exam scores (int) and storing the result in a float variable, C automatically converts int to float.

When to Use It:

Implicit type casting is automatically used in C when performing arithmetic operations between different data types, such as adding an integer to a float. You don’t need to do anything to trigger this type of casting.

Example:

#include <stdio.h>
int main() {
    int num1 = 5;       // integer value
    float num2 = 6.3;   // floating-point value
    // Implicit casting: int to float
    float result = num1 + num2;  
    printf("Result: %.2f\n", result);  // Output the result
    return 0;
}

Output:

Result: 11.30

Explanation:

  • num1 is automatically converted to a float before being added to num2 (which is already a float).
  • The C compiler performs the conversion for you, so the addition of num1 and num2 results in a float value.
  • The result is 11.30 because implicit type casting converted the integer 5 to 5.0 before performing the addition.

Explicit Type Casting (Manual Type Casting)

Explicit Type Casting happens when you, the programmer, manually convert a value from one data type to another. This is done using the casting operator (new_data_type). Explicit casting is required when you need to convert a larger data type to a smaller one (e.g., from float to int), which may cause loss of data or precision.

For example, when dealing with hardware-level programming or large data processing, explicit type casting is often needed to prevent overflows.

When to Use It:

You use explicit type casting when you need to manually control the conversion between data types, particularly when there’s a possibility of data loss or truncation, like converting a float to an int.

Example:

#include <stdio.h>
int main() {
    float num1 = 9.75;   // floating-point value
    int num2;             // integer value
    // Explicit casting: float to int
    num2 = (int) num1;    
    printf("Converted value: %d\n", num2);  // Output the converted value
    return 0;
}

Output:

Converted value: 9

Explanation:

  • In this example, the explicit type casting syntax (int) num1 is used to convert the float value 9.75 into an integer.
  • Since int can only hold whole numbers, the decimal part is discarded, and only 9 is stored in num2.
  • This shows how explicit casting gives you control over the conversion, but it also highlights the potential for data loss (the decimal .75 is ignored).

Also Read: Top 3 Open Source Projects for C [For Beginners To Try]

Now that you know the types, let’s tackle some common issues with type casting and how to avoid them.

Common Issues with Type Casting

When working with type casting in C, there are a few common issues that you may encounter, particularly when converting between incompatible data types.

Let's go over some of these common pitfalls, see how to avoid them, and explore solutions with examples.

1. Loss of Data During Casting (e.g., converting from float to int)

One of the most frequent issues with type casting is loss of data. This occurs when you convert from a larger data type, like a float, to a smaller one, like an int. Since int cannot hold decimal places, the fractional part of the float is lost during the conversion.

Improper type casting can cause logic errors or incorrect program output, such as rounding issues in financial calculations when casting a double to an int or precision loss in scientific computing when converting a float to an int.

Example: Loss of Data

#include <stdio.h>
int main() {
    float num1 = 8.75;   // float value
    int num2;
    // Explicit casting: float to int (data loss)
    num2 = (int) num1;
    printf("Converted value: %d\n", num2);  // Output the result
    return 0;
}

Output:

Converted value: 8

Explanation:

  • (int) num1: The explicit type casting here converts num1 (which is 8.75) from a float to an int. The fractional part .75 is truncated, so the result is 8.
  • Data loss occurs, and it's important to be aware that casting a float to int will always drop any decimal values.

Solution to Avoid Data Loss:

  • If you need to preserve the decimal portion, consider rounding or storing the result as a float or double instead of casting it to int.
  • For rounding, you can use the round() function in C:
#include <stdio.h>
#include <math.h>
int main() {
    float num1 = 8.75;
    int num2 = (int) round(num1);  // Round before casting
    printf("Rounded and converted value: %d\n", num2);
    return 0;
}

Output:

Rounded and converted value: 9

Another critical issue to consider when casting between data types is how values may overflow or underflow, leading to unexpected results.

2. Overflow or Underflow When Converting Larger Data Types to Smaller Ones

Another issue that may arise is overflow or underflow when casting from a larger data type to a smaller one. This happens when the value being converted exceeds the range of the smaller data type.

Example:

#include <stdio.h>
int main() {
    long long large_num = 1234567890;  // Large number
    int small_num;
    // Explicit casting: long long to int (possible overflow)
    small_num = (int) large_num;
    printf("Converted value: %d\n", small_num);  // Output the result
    return 0;
}

Output:

Converted value: -1610612736

Explanation:

  • large_num is a long long value that exceeds the maximum value that an int can store. When casting it to int, the value overflows, and you get an unexpected negative result.
  • This is because int has a limited range (typically from -2^31 to 2^31-1), and the number exceeds that range.

Solution to Avoid Overflow/Underflow:

  • Always check the range of the data types involved in the casting. If you're casting to a smaller type, ensure the value is within the range that can be represented.
  • Use appropriate data types (like long long or double) if you expect large values that might cause overflow.

3. Incompatibility Between Pointer Types and Data Types

Another common issue is casting between pointer types and non-pointer types. This can lead to undefined behavior if you're not careful about how the memory is handled.

Example:

#include <stdio.h>
int main() {
    float num1 = 5.5;
    int *ptr;
    // Incorrect type casting: float to int pointer
    ptr = (int *) &num1;  // Casting pointer type
    printf("Pointer value: %d\n", *ptr);  // Dereferencing pointer
    return 0;
}

Output (Undefined Behavior):

Pointer value: 1092616192

Explanation:

  • (int *) &num1: This casts the address of num1 (which is a float) to an int pointer. Dereferencing this pointer leads to unpredictable behavior because the types are incompatible.
  • Since num1 is a float and the pointer is cast as an int, dereferencing the pointer will interpret the memory differently, producing garbage values.

Solution to Avoid Pointer Casting Issues:

  • Avoid casting between incompatible pointer types. If you need to work with the value at a pointer, make sure the types match, or consider using void * if type independence is required.

Now that you know the common pitfalls, let’s dive into some best practices for type casting in C to keep your code sharp and error-free.

Best Practices for Type Casting in C

Let’s explore some of the best practices that will help you use type casting in C with examples effectively.

1. Minimize Type Casting

While type casting in C is a powerful tool, overusing it can make your code harder to understand and debug. Avoid excessive casting, especially when it can be avoided by using the correct data types in the first place.

For example, if you're working with integers, use int instead of casting a float to int unnecessarily. Try to use the most appropriate type for your data from the beginning to reduce the need for conversions.

Minimizing type casting enhances performance in critical applications by reducing unnecessary conversions, such as avoiding repeated float-to-int casts in a high-frequency trading algorithm.

Additionally, casting between signed and unsigned types can lead to undefined behavior—for example, comparing -1 (signed) with 0 (unsigned) may produce unexpected results, making it essential to use appropriate data types.

2. Be Mindful of Data Loss

One of the key issues with what is type casting in C is the potential data loss when converting from larger types (like float or double) to smaller types (like int). Always be aware of the consequences of casting, especially when truncating decimal values or handling large numbers.

Tip: Before casting, check if the value fits into the target data type to avoid unexpected behavior.

Example:

#include <stdio.h>
int main() {
    float num = 10.75;
    int num2 = (int) num;  // Explicit casting, potential data loss
    printf("Result: %d\n", num2);  // Expect 10, not 10.75
    return 0;
}

Output:

Result: 10

Explanation:

Here, the decimal part .75 is discarded due to the explicit type cast from float to int. Always check whether truncating the decimal value is acceptable in your logic.

3. Use Explicit Type Casting When Necessary

If you need to convert between incompatible types, use explicit type casting in C. This gives you control over the conversion and ensures you're aware of any potential data loss or other consequences.

For instance, if you need to convert a double to an int without losing data unnecessarily, explicitly cast it and handle the rounding yourself if needed:

#include <stdio.h>
#include <math.h>
int main() {
    double num = 9.99;
    int num2 = (int) round(num);  // Round before casting to int
    printf("Rounded Result: %d\n", num2);
    return 0;
}

Output:

Rounded Result: 10

Explanation:

By using round(), you prevent truncation of the decimal part, ensuring that 9.99 is properly rounded to 10 before casting to int.

4. Avoid Casting Between Incompatible Pointers

When casting between pointer types, ensure that the data types are compatible. Casting pointers from one type to another can lead to undefined behavior, especially when you cast between different types, such as casting a float * to int *. Always ensure the pointer types match, or use void * if you need a generic pointer type.

5. Use Proper Indentation and Comments

When working with type casting in C with example, it's crucial to maintain clean, readable code. Proper indentation helps keep track of nested type casts, and comments can explain why casting is necessary, making the code easier to maintain.

Also Read: Top 25+ C Programming Projects for Beginners and Professionals

Try experimenting with both implicit and explicit type casting to deepen your understanding of how C handles data conversion. The more you practice, the clearer these concepts will become!

MCQs on Type Casting in C

1. What is type casting in C?

a) Changing a pointer’s address

b) Converting one data type to another

c) Creating new data types

d) Changing variable names

2. What is implicit type casting?

a) When the programmer writes the conversion

b) Automatic conversion by the compiler

c) Casting done using cast() function

d) It is not allowed in C

3. What is explicit type casting?

a) Type conversion using assignment

b) Compiler decides the cast

c) Manually converting using syntax like (int)x

d) Using float and double together

4. What is the result of this code?

float x = 10.5;
int y = x;

a) y = 10.5

b) y = 10

c) Compilation error

d) y = 11

5. Which of these is a correct example of explicit casting?

a) int x = 5.0;

b) int x = (int)5.75;

c) float x = 3;

d) char x = 'A';

6. Which statement about implicit casting is true?

a) It loses data safely

b) Converts smaller type to larger automatically

c) Converts larger to smaller without warning

d) Always results in float

7. What is the result of:

int a = 5;
float b = 2;
printf("%f", a / b);

a) 2.5

b) 2.0

c) 2

d) Compiler error

8. What happens when you cast a float to int?

a) Rounds to nearest whole number

b) Truncates decimal part

c) Throws error

d) Adds type suffix

9. You write:

float a = 7/2;

What will be the value of a?**

a) 3.5

b) 3

c) 3.0

d) Error

10. In a calculation:

int x = 10;
int y = 3;
float z = x / y;

What should you change to get 3.33 as output?

a) Use z = x / y.0;

b) Cast one variable: z = (float)x / y;

c) Use float division syntax

d) Multiply by 1.0

11. A programmer casts an int* to float* and reads memory. What could happen?

a) Safe execution

b) Compiler optimization

c) Undefined behavior

d) Segmentation fault

How Can upGrad Help You Master Type Casting in C?

Now that you've tested your knowledge of type casting in C, it’s time to deepen your understanding. upGrad offers comprehensive courses that dive deeper into C programming, helping you master type casting and other essential concepts.

Explore type casting in C and enhance your skills with hands-on projects and interactive learning.

upGrad provides expert guidance and hands-on projects that enhance your C programming skills, helping you master concepts like type casting, memory management, and efficient code optimization for real-world applications.

Check out some of the best upGrad’s courses:

You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!

Similar Reads:

Explore C Tutorials: From Beginner Concepts to Advanced Techniques

Array in C: Introduction, Declaration, Initialisation and More

Exploring Array of Pointers in C: A Beginner's Guide

What is C Function Call Stack: A Complete Tutorial

Binary Search in C

Constant Pointer in C: The Fundamentals and Best Practices

Find Out About Data Structures in C and How to Use Them?

FAQs

1. Can type casting cause unexpected behavior in C?

Yes, type casting in C can lead to unexpected behavior if not done carefully, such as data loss or overflow, especially when casting between incompatible data types.

2. Is implicit type casting always safe in C?

No, while implicit type casting in C is automatically handled, it can sometimes lead to precision loss when converting from a larger data type (like double) to a smaller one (like int).

3. How can I prevent data loss when using type casting in C with example?

Use explicit type casting when converting from larger to smaller data types, and ensure the data fits the target type to avoid truncation or overflow.

4. What happens if I cast incompatible pointer types in C?

Casting incompatible pointers can result in undefined behavior or memory access errors, so ensure pointer types match or use void * when necessary.

5. Can I use type casting in C with example to convert complex data types?

Yes, you can use type casting for complex types, but be cautious. For example, casting between struct types requires specific handling to avoid breaking the data structure.

6. What is the risk of casting from float to int in C?

Type casting in C with example from float to int truncates the decimal part, which could lead to losing precision in the result.

7. When should I use explicit type casting in C?

Use explicit type casting in C when you need precise control over the conversion of one type to another, especially when working with mixed data types or when precision is critical.

8. How does type casting in C help in function calls?

Type casting in C ensures that arguments passed to a function match the expected data types, preventing errors and ensuring correct function behavior.

9. Can implicit type casting change the outcome of arithmetic operations in C?

Yes, implicit type casting in C can change the outcome of arithmetic operations by automatically converting types. For example, adding an integer to a float will result in a float, potentially affecting the precision.

10. What is the impact of casting larger data types to smaller ones in C?

Casting larger data types (e.g., double) to smaller ones (e.g., int) can lead to data loss and truncation, especially if the original value exceeds the smaller type’s range.

11. Can I safely cast between long long and int types in C?

Casting between long long and int may cause overflow if the value exceeds the range of the target type. Always ensure the value is within the valid range before casting.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.