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
View All
View All
View All
View All
View All
View All
View All
View All
View All
c tutorial

Explore C Tutorials: From Begi…

  • 132 Lessons
  • 22 Hours

Type Casting in C

Updated on 12/02/20254,119 Views

Type casting in C refers to converting a variable from one data type to another, such as converting an int to a float. This is critical in C programming because it ensures compatibility between different data types, prevents data loss, and optimizes memory usage.

 In C programming, you’ll often encounter situations where you need to work with different data types together, leading to type conversion issues. 

Understanding what is type casting in C and how it works will help you handle these situations effectively. In this guide, we’ll explore type casting in C with examples to give you a clear understanding of how to use it properly. Let’s dive into the details!

Boost your C programming skills with our Software Development courses — take the next step in your learning journey! 

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.

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!

How Well Do You Know Type Casting in C? 10 Clever MCQs

Test your understanding of type casting in C with these questions! From basic concepts to advanced applications, let’s see how well you know type casting in C.

1. What is the main purpose of type casting in C?

A) To combine multiple variables

B) To convert a variable from one data type to another

C) To change the size of a data type

D) To assign one variable to another

2. Which of the following is an example of implicit type casting in C?

A) Converting a float to int manually

B) Converting an int to float automatically in an expression

C) Converting a pointer type to an integer

D) Using (type) to cast between types

3. What happens if you cast a float to an int in C?

A) The fractional part is rounded

B) The fractional part is truncated

C) The integer part is discarded

D) The program will throw an error

4. Which of the following is true about explicit type casting in C?

A) It happens automatically when needed

B) It requires using the (new_data_type) syntax

C) It can only be used for integer types

D) It only works with float and int

5. When should you use explicit type casting in C?

A) When converting from a larger type to a smaller type

B) When converting between compatible data types

C) When automatic casting is already handled by the compiler

D) When working with pointers only

6. What is the risk of type casting in C with example when converting from a larger to a smaller data type?

A) The program may run slower

B) The data may be lost or truncated

C) The code will be more efficient

D) It will always result in an error

7. What does the following code do: (int) 7.9?

A) Converts the float 7.9 to the integer 8

B) Converts the float 7.9 to the integer 7

C) Rounds 7.9 to the nearest integer

D) Returns an error

8. How do you avoid data loss when using type casting in C?

A) Use the round() function before casting

B) Use a larger data type when converting

C) Avoid casting altogether

D) Use only implicit casting

9. What’s the primary difference between implicit and explicit type casting in C?

A) Implicit casting requires the programmer to specify the type

B) Explicit casting is done automatically by the compiler

C) Implicit casting occurs automatically, while explicit casting requires manual intervention

D) There is no difference

10. In which situation would explicit type casting be necessary?

A) When working with arithmetic operations between integers

B) When converting between different pointer types

C) When working with similar data types

D) When converting a double to int manually

Understanding type casting in C is just the beginning—keep building your C programming skills with expert-led courses and hands-on learning.  

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

+918045604032

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.