Cast Operator in C

Type casting in C is a fundamental concept that allows you to convert a variable from one data type to another. This tutorial will guide you through the essentials of the cast operator in C, ensuring a solid understanding for both beginners and intermediate programmers.​

What is Type Casting in C?

Type casting, also known as type conversion, is the process of converting a variable from one data type to another. This is particularly useful when performing operations between different data types or when you need to store a value in a variable of a different type.​

Syntax of the Cast Operator

The general syntax for type casting in C is:​

(type_name) expression;

Here, type_name is the data type you want to convert the expression to.​

advertisement

Types of Type Casting

In C, type casting is categorized into two types:​

1. Implicit Type Casting (Automatic)

Implicit casting occurs when the compiler automatically converts a smaller data type to a larger data type to prevent data loss.​

Example:

Free 30-Day Python Certification Bootcamp is Live. Join Now!
#include <stdio.h>
 
int main()
{
    int mcqScore = 4;
    float percentage;
 
    percentage = mcqScore / 5; 
    printf("Percentage (int/int): %.2f\n", percentage);
 
    percentage = mcqScore / 5.0;  // Implicit casting: int promoted to float
    printf("Percentage (int/float): %.2f\n", percentage);
 
    return 0;
}

Output:

Percentage (int/int): 0.00
Percentage (int/float): 0.80

This C program shows how dividing integers vs floats affects the result. It sets mcqScore = 4 and first divides it by 5 (both ints), which gives 0 due to integer division, then stores it in percentage. Next, it divides mcqScore by 5.0, making it a float division, which gives 0.80. Both results are printed with two decimal places

2. Explicit Type Casting (Manual)

Explicit casting is done manually by the programmer using the cast operator.​

Example:

#include <stdio.h>
 
int main() {
    float mcqScore = 4.7;
    int roundedScore;
 
    roundedScore = (int)mcqScore;
 
    printf("Your score is: %d (rounded)\n", roundedScore);
    return 0;
}

Output:

Your score is: 4 (rounded)

This C program shows how to convert a float to an int using type casting. It sets mcqScore = 4.7 and then casts it to an integer with (int)mcqScore. This removes the decimal part, so roundedScore becomes 4. It prints: “Your score is: 4 (rounded)”.

advertisement

Why Use Type Casting?

Type casting is essential in scenarios such as:​

  • Data Conversion: When you need to convert data from one type to another, especially in arithmetic operations.
  • Memory Management: To ensure that variables use memory efficiently by converting to appropriate data types.
  • Function Arguments: When passing arguments to functions that expect a specific data type.
  • Avoiding Data Loss: To prevent unintended data loss during assignments and calculations.​

Practical Examples

Example 1: Preventing Integer Division

#include <stdio.h>
 
int main() {
    int total = 7, questions = 2;
    float average;
 
    average = (float)total / questions;
 
    printf("Average score per question = %.2f\n", average);
    return 0;
}

Output:

Average score per question = 3.50

This C program calculates the average score per question. It sets total = 7 and questions = 2. To get a decimal result, it uses type casting: (float)total, which converts total to a float before division. This gives an accurate average. The result is printed with two decimal places.

Example 2: Memory Allocation with malloc (Casting Pointers)

#include <stdio.h>
#include <stdlib.h>
 
int main() {
    int *arr;
    arr = (int *)malloc(5 * sizeof(int));
 
    for (int i = 0; i < 5; i++) {
        arr[i] = i * 10;
        printf("%d ", arr[i]);
    }
 
    free(arr);
    return 0;
}

Output:​

0 10 20 30 40

This C program uses dynamic memory allocation with malloc. It creates space for 5 integers using malloc(5 * sizeof(int)) and stores the address in arr. A for loop fills the array with values 0, 10, 20, 30, 40 and prints them. After use, the memory is freed using free(arr).

Common Pitfalls

  • Data Loss: Casting from a larger to a smaller data type can lead to loss of data.
  • Precision Errors: Casting floating-point numbers to integers truncates the decimal part, which might not be the desired behavior.
  • Undefined Behavior: Casting pointers to incompatible types can lead to undefined behavior.​

Best Practices

  • Use Explicit Casting When Necessary: Always cast explicitly when there’s a possibility of data loss or when clarity is needed.
  • Be Cautious with Implicit Casting: Relying too much on implicit casting can lead to unexpected results, especially with signed and unsigned types.
  • Understand Data Type Sizes: Know the size and range of data types to prevent overflows and underflows during casting.
  • Avoid Unnecessary Casting: Don’t cast variables unnecessarily, as it can make the code less readable and more error-prone.​

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.