top

Search

C Tutorial

.

UpGrad

C Tutorial

Type Casting in C

Type Casting in C is a fundamental concept that is extensively utilised in programming. It's the process of converting one data type into another to ensure compatibility and smooth execution of the code. Type casting aids in avoiding data loss and bugs that might occur due to mismatched data types during calculations or data manipulation.

Let’s dive in to explore the depths of type casting in C and its various types to understand their accurate implementation through examples and more!

Syntax for Type Casting in C

The syntax for type casting is quite simple

(data_type) variable_name;

Here, data_type is the desired data type to which we want to convert, and variable_name is the name of the variable that needs to be converted.

Type Casting in C: Types and Their Examples

Primarily, two types of type casting in C can be explored. These include- Implicit Type Casting and Explicit Type Casting.

1. Implicit Type Casting in C 

Implicit type casting, uncommonly referred to as automatic type conversion, is a feature of the C language that allows the compiler to automatically convert one data type to another when necessary. It occurs without any explicit instructions from the programmer and aims to ensure compatibility and prevent data loss or errors.

In C, implicit type casting is based on a set of rules defined by the language. These rules establish a hierarchy of data types, and when an operation involves different data types, the compiler automatically performs the conversion to the higher-ranked data type to maintain precision and avoid loss of information.

Implicit Type Casting in C: Examples

Let's consider an example to illustrate implicit type casting:

int x = 10;
float y = 5.5;
float result;

result = x + y;

In this example, the variable x is an int type, and the variable y is a float type. The addition operation x + y involves two different data types. The C compiler performs implicit type casting and converts x to a float type before performing the addition. The result will be stored in the result variable, which is also of type float.

Implicit type casting ensures that the result of the operation has sufficient precision and avoids loss of data. It allows for the seamless integration of different data types in expressions and calculations.

Converting Char to Int

One example of implicit type casting in C is the conversion of char to int:

char ch = 'A';
int num = ch;

printf("%d", num);

In this case, the ASCII value of 'A' (65) will be printed.

Hierarchy of Arithmetic Conversion

The hierarchy of data types in C, from highest to lowest, is as follows:

1. long double

2. double

3. float

4. unsigned long long int

5. long long int

6. unsigned long int

7. long int

8. unsigned int

9. int

10. char and signed char

11. unsigned char

Implicit type casting follows the hierarchy rules when performing operations involving different data types. The compiler converts the data type of the operand with the lower rank to the data type with the higher rank.

For example, consider the expression int_var = int_var + float_var;. In this case, the float_var will be implicitly converted to an int type before the addition operation because int has a higher rank in the hierarchy compared to float.

2. Explicit Type Casting in C

Explicit type casting in C, as the name suggests, is performed explicitly by the programmer. This is typically required when we want to demote a greater data type variable to a comparatively smaller one or convert it between unrelated types like float to int.

Here's an example to illustrate explicit type casting:

double x = 10.7;
int y = (int) x;

printf("%d", y);

In this case, the decimal part of 'x' (.7) is lost, and the output will be '10'.

C Language In-built Data Type Casting Functions

C language also provides some in-built functions for type casting, such as atoi(), atol(), atof(), etc. These functions are used to convert string type variables to int, long, and float, respectively.

Type Conversion and Type Casting in C: Navigating Differences

In C programming, the terms "type conversion" and "type casting" are often used interchangeably, but they have distinct meanings and purposes. Understanding the differences between these two concepts is crucial for writing correct and efficient code. Let's explore the dissimilarities between type conversion and type casting:

Type Conversion:

Type conversion, also referred to as implicit type casting or automatic type conversion, occurs when the compiler automatically converts one data type to another to ensure compatibility and maintain data integrity. It is performed by the compiler without any explicit instructions from the programmer.

Key characteristics of type conversion:

  • It is automatic and performed by the compiler during compilation.

  • The purpose of type conversion is to prevent data loss or errors that may occur due to incompatible data types.

  • Type conversion generally occurs when assigning one data type's value to another data type's variable.

  • It is based on the rules defined by the C language, such as the hierarchy of arithmetic conversions.

Type Casting:

Type casting or explicit type conversion involves the programmer manually converting one data type to another. It is done explicitly using the casting operator (data_type) followed by the variable or expression to be cast.

Key characteristics of type casting:

  • It is a manual operation explicitly performed by the programmer.

  • The purpose of type casting is to convert a variable from one data type to another, which may involve demotion (narrowing) or promotion (widening) of data.

  • Type casting is used when the programmer wants to override the default behaviour of type conversion or explicitly convert between unrelated data types.

  • It allows for more control and precision over the conversion process but may result in potential data loss or truncation.

Differences Between Type Conversion and Type Casting:

Let’s navigate points that make type conversion and type casting distinct from each other with the help of this table.

Type Conversion

Type Casting

Automatic conversion performed by the compiler

Manual conversion performed by the programmer

Maintains data integrity and prevents data loss or errors

Allows explicit control over the conversion process

Based on predefined rules and hierarchy

Overrides default conversion behaviour

Implicitly converts between compatible data types

Explicitly converts between related or unrelated types

Cannot be applied to all situations

Can be applied to a wider range of situations

Examples: assigning a float to an int, char to int

Examples: (int) float_var, (char) int_var

Understanding the contrasts between type conversion and type casting helps programmers make informed decisions regarding data manipulation and compatibility in their C programs. By leveraging these concepts effectively, you can ensure your code's accuracy, efficiency, and correctness.

Type Casting Advantages in the C Language

Type casting in the C language offers several advantages that contribute to the efficiency and flexibility of the code. Let's explore some of these advantages:

1. Ensuring Compatibility: Type casting allows for seamless compatibility between different data types. It enables the manipulation of variables of different types in a unified manner, reducing the need for complex workarounds or conditional checks. By converting variables to the desired types, you can perform operations and calculations without encountering type-related errors.

2. Preventing Data Loss and Errors: Type casting helps prevent data loss that may occur when assigning values of one data type to variables of another data type. For example, when converting a larger data type to a smaller one, explicit type casting notifies the programmer that there may be a potential loss of precision or truncation of data. This awareness enables you to make informed decisions and take appropriate measures to handle potential risks.

3. Facilitating Function Utilisation: In some cases, functions in C require specific data types as arguments. Type casting allows you to convert variables to the required types, enabling the utilisation of a wide range of functions. For instance, if a function expects an integer argument but you have a floating-point variable, explicit type casting can help you pass the converted value to the function without any issues.

4. Arithmetic and Logical Operations: Type casting plays a crucial role in arithmetic and logical operations involving different data types. By converting variables to a common data type, you can perform calculations and comparisons efficiently. For example, if you have an operation involving both integers and floats, explicit type casting can ensure that the result is obtained in the desired data type.

5. Enhancing Code Flexibility: Type casting provides greater flexibility when working with complex data structures and algorithms. It enables the programmer to seamlessly manipulate and combine variables of different data types, facilitating the implementation of intricate logic and algorithms. This flexibility empowers developers to create efficient and versatile code.

Overall, type casting in the C language improves code robustness, data integrity, and efficiency. By appropriately leveraging type casting, programmers can easily handle different data types, avoid errors, and utilise a wider range of functions and operations. Understanding the advantages of type casting allows you to make informed code design and implementation decisions.

Practice Problems on Type Casting in C

Here are a few challenging problems that will help you test your understanding of type casting in C:

1. Floating-Point to Integer Conversion: Write a program that accepts a floating-point number and convert it into an integer using explicit type casting. Make sure to handle both positive and negative numbers.

Hint: Remember that explicit type casting can be done using the format (int)variable.

2. Character to ASCII Conversion: Write a program that accepts a character and prints its ASCII value using implicit type casting.

Hint: You don't need to use any special function to convert a char to an int. In C, a char is automatically converted to its ASCII equivalent when used in an integer context.

3. Data Promotion: Write a program where you have a variable of a smaller data type (like char or int), and you perform an operation on it with a variable of a larger data type (like float or double). Print out the result and observe the type of the result.

Hint: Implicit type casting will happen here. The variable of the smaller data type will be promoted to the larger data type before the operation.

4. Mixing Different Types: Write a program where you perform arithmetic operations between int, float, and char variables. Observe the results carefully and try to deduce the type of the result in each case.

Hint: The hierarchy of arithmetic conversions rule is followed when performing arithmetic operations on different data types. You might need to explicitly cast some variables to get the desired result.

5. Multi-level Type Casting: Write a program that involves multi-level type casting. For example, convert a double to int, then that int to char, and observe the results.

Hint: Be careful with multi-level type casting. Each conversion can potentially lose some data.

6. Using Casting Functions: Write a program that accepts a string of numbers and uses casting functions like atoi(), atof() to convert the string to an integer and a float, respectively.

Hint: Remember to include the stdlib.h header file to use these casting functions.

Remember, the key to mastering type casting in C is practice. By solving these problems, you can deepen your understanding of type casting and how it works in different scenarios.

To sum up, mastering the concept of type casting in C is crucial for any C programmer. It allows for better data manipulation, reduces errors, and enhances the overall efficiency of the code. In case you are eager to further deepen your understanding of C or other programming languages, we have your back! 

Consider exploring Data Science & Analytics Bootcamp on upGrad- a comprehensive course driven to strengthen your programming skills while enabling you to leverage the acquired skills in the growing field of data science. 

FAQs

1. What is Type Casting in C?

Type casting in C is the process of converting one data type into another to ensure compatibility and smooth execution of the code.

2. What are the types of type casting in C?

Type casting in C further branches into two different types: Implicit type casting and Explicit type casting.

3. What is the difference between type conversion and type casting in C? 

Type conversion is usually automatic, done by the compiler, to prevent data loss or errors. Type casting, on the other hand, is manually done by the programmer and can be either promotion or demotion.

Leave a Reply

Your email address will not be published. Required fields are marked *