- C Programming Tutorial
- C - Home
- Basics of C
- C - Introduction
- C - Features
- C - Basics
- C - History
- C - Structure of C Program
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Tokens
- C - Keywords
- C - Identifiers
- C - User Input
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Integer Promotions
- C - Type Conversion
- C - Type Casting
- C - Booleans
- Constants and Literals in C
- C - Constants
- C - Literals
- C - Escape sequences
- C - Format Specifiers
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Unary Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Misc Operators
- Decision Making in C
- C - Decision Making
- C - if statement
- C - if...else statement
- C - nested if statements
- C - switch statement
- C - nested switch statements
- Loops in C
- C - Loops
- C - While loop
- C - For loop
- C - Do...while loop
- C - Nested loop
- C - Infinite loop
- C - Break Statement
- C - Continue Statement
- C - goto Statement
- Functions in C
- C - Functions
- C - Main Function
- C - Function call by Value
- C - Function call by reference
- C - Nested Functions
- C - Variadic Functions
- C - User-Defined Functions
- C - Callback Function
- C - Return Statement
- C - Recursion
- Scope Rules in C
- C - Scope Rules
- C - Static Variables
- C - Global Variables
- Arrays in C
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays
- Pointers in C
- C - Pointers
- C - Pointers and Arrays
- C - Applications of Pointers
- C - Pointer Arithmetics
- C - Array of Pointers
- C - Pointer to Pointer
- C - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Function Pointers
- C - Pointer to an Array
- C - Pointers to Structures
- C - Chain of Pointers
- C - Pointer vs Array
- C - Character Pointers and Functions
- C - NULL Pointer
- C - void Pointer
- C - Dangling Pointers
- C - Dereference Pointer
- C - Near, Far and Huge Pointers
- C - Initialization of Pointer Arrays
- C - Pointers vs. Multi-dimensional Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Special Characters
- C Structures and Unions
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Lookup Tables
- C - Dot (.) Operator
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- File Handling in C
- C - Input & Output
- C - File I/O (File Handling)
- C Preprocessors
- C - Preprocessors
- C - Pragmas
- C - Preprocessor Operators
- C - Macros
- C - Header Files
- Memory Management in C
- C - Memory Management
- C - Memory Address
- C - Storage Classes
- Miscellaneous Topics
- C - Error Handling
- C - Variable Arguments
- C - Command Execution
- C - Math Functions
- C - String Functions
- C - Static Keyword
- C - Random Number Generation
- C - Command Line Arguments
C Programming - C Type Casting
![]() Share with a Friend |
C Programming - C Type Casting
Type casting in C refers to converting a variable from one data type to another explicitly. Unlike implicit type conversion (done automatically by the compiler), type casting is done manually by the programmer to achieve specific results or handle data safely.
Types of Type Casting in C
- Implicit Type Casting:
- Also called type promotion.
- Automatically done by the compiler to prevent data loss during operations involving mixed data types.
- Example: int is automatically promoted to float in arithmetic operations.
- Explicit Type Casting:
- Done manually by the programmer.
- Involves the use of a cast operator (type).
Syntax of Explicit Type Casting
C
(type) expression;
- type: The desired data type to cast the variable or expression.
- expression: The variable or value to be converted.
Examples of Type Casting
- Casting Integers to Float
C
#include <stdio.h>
int main() {
int a = 10, b = 3;
float result;
result = (float)a / b; // Explicit cast 'a' to float
printf("Result: %.2f\n", result); // Output: 3.33
return 0;
}
Here:
- The integer a is explicitly cast to float before division to ensure accurate results.
- Casting Float to Integer
C
#include <stdio.h>
int main() {
float pi = 3.14159;
int int_pi;
int_pi = (int)pi; // Truncates the decimal part
printf("Integer value: %d\n", int_pi); // Output: 3
return 0;
}
Here:
- The float value pi is cast to int, resulting in truncation of the fractional part.
- Casting Characters to Integer
C
#include <stdio.h>
int main() {
char ch = 'A';
int ascii_value;
ascii_value = (int)ch; // Cast character to integer
printf("ASCII Value of %c: %d\n", ch, ascii_value); // Output: ASCII Value of A: 65
return 0;
}
Here:
- The char value 'A' is cast to its ASCII equivalent.
- Casting Integer to Unsigned
C
#include <stdio.h>
int main() {
int a = -10;
unsigned int b;
b = (unsigned int)a; // Cast signed to unsigned
printf("Unsigned Value: %u\n", b); // Output depends on system (e.g., 4294967286)
return 0;
}
Here:
- Casting a negative signed integer to unsigned results in an unexpected large value due to representation.
Use Cases of Type Casting
- Prevent Data Loss:
- Ensures correct results in arithmetic operations.
C
float result = (float)5 / 2; // Avoids integer division
- Accessing Data in Low-Level Programming:
- Used to reinterpret memory or data in a different form (e.g., pointer typecasting).
- Compatibility Between Data Types:
- Ensures smooth operation in functions expecting specific data types.
- Truncation or Rounding:
- Allows manual control over how data is truncated or rounded.
Pitfalls of Type Casting
- Loss of Precision:
- Casting from float or double to int removes the fractional part.
C
int x = (int)3.9; // Results in 3
- Overflow and Underflow:
- Casting between signed and unsigned types or to smaller types can lead to overflow.
C
char x = (char)300; // Value wraps around in smaller range
- Undefined Behavior:
- Improper casting, especially with pointers, can result in undefined behavior.
Type Casting with Pointers
In C, type casting with pointers allows interpreting data in memory differently.
Example: Casting to void* and Back
C
#include <stdio.h>
int main() {
int num = 42;
void *ptr = (void *)# // Cast 'int*' to 'void*'
int *int_ptr = (int *)ptr; // Cast back to 'int*'
printf("Value: %d\n", *int_ptr); // Output: 42
return 0;
}
Key Points
- Type casting enables controlled conversion between data types.
- Explicit casting must be used cautiously to avoid unexpected results.
- Always ensure the target type can handle the source value without data loss or overflow.
Summary of Common Type Casting
| Source Type | Target Type | Effect |
|---|---|---|
|
float → int |
Truncates fractional part. |
|
|
int → float |
Adds precision for operations. |
|
|
char → int |
Converts to ASCII equivalent. |
|
|
int → char |
May result in overflow for large values. |
|
|
signed → unsigned |
Converts but may wrap negative values. |
Type casting is a powerful tool in C, enabling precision and flexibility in programming when used judiciously.
