SlideShare a Scribd company logo
1 of 9
Typecasting in C
Typecasting is simply a mechanism
by which we can change the data type of a
variable, no matter how it was originally
defined. When a variable is typecasted into a
different type, the compiler basically treats the
variable as of the new data type.
Example:
#include<stdio.h>
int main(void)
{
int a=5,b=8;
float c = 0, d = 0;
c = a/b;
printf("n [%f] n",c);
d = (float)a/(float)b;
printf("n [%f] n",d);
return 0;
}
In the above example, first we divide 'a' by 'b' without
typecasting. While in the second attempt we typecast both 'a'
and 'b' to float and then divide them.
So, what happens is, in the first attempt, the compiler
knows both 'a' and 'b' are integers so it ignores the floating
part of the result and stores the result of a/b in a temporary
integer variable and then assign the value of this temporary
integer variable to 'c'. So despite of 'c' being a float, the final
value that 'c' gets is an integer ie '0' in this case.
While in the second attempt, as both 'a' and 'b' are
individually typecasted as 'float', so this typecasting makes
compiler think as if both 'a' and 'b' are floats, so the compiler
retains the floating part of the result and assigns the float
value to 'c'.
The output of the above program :
[0.000000]
[0.625000]
CASTING DATA TYPES:
Result type of arithmetic phrase depends of
operand types inside it. When a phrase is consisted of
various data types, result type is set by defined casting
rules. Rules for casting various data types in C
language are oriented to higher data type. There are
two ways of casting data types in C:
Implicit(automatic) casting
2. Explicit(given) casting
1.
Implicit Casting (automatic transformation)
works in a way that a variable (operand) of data
type that is smaller in length (than data type of
second variable) (operand), transforming
internally to variable of data type with longer
number length. It may sound mixed up.

Example:
int a;
float f, g;
g = a + f; // a transforms to float
Explicit Casting (given transformation) of data types
has higher priority then automatic transformation.
General declaration of explicit (given) cast (cast
operator):
(data_type) operand
Operand can be variable or phrase.

Example:
a = (int) c;
b = (double)d + c;
Some examples:
Example 1:
float a = 5.25;
int b = (int)a;
/*Explicit casting from float to
int. The value of b here is 5*/
Example 2:
char c = ’A’;
int x = (int)c;
/*Explicit casting from char to
int. The value of x here is 65: the ASCII code of
‘A’*/
Example 3:
int x=7, y=5 ;
float z;
z=x/y;
/*Here the value of z is 1*/
If we want to get the exact value of 7/5 then
we need explicit casting from int to float:
int x=7, y=5;
float z;
z = (float)x/(float)y; /*Here the value of z is
1.4*/
Example 4:
int x=70;
char c =(char)x; /*The value of c here is F:
the ASCII code of 70*/
THE END

More Related Content

What's hot (20)

Arrays in c language
Arrays in c languageArrays in c language
Arrays in c language
 
User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Type conversion
Type conversionType conversion
Type conversion
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Strings
StringsStrings
Strings
 
Data Types In C
Data Types In CData Types In C
Data Types In C
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
File in C language
File in C languageFile in C language
File in C language
 
If statements in c programming
If statements in c programmingIf statements in c programming
If statements in c programming
 
Structure in C
Structure in CStructure in C
Structure in C
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
 
Types of function call
Types of function callTypes of function call
Types of function call
 
C Pointers
C PointersC Pointers
C Pointers
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 

Viewers also liked

Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityAakash Singh
 
Annamaria D'urzo - I sistemi informatici SITIC SIGIS Output-CN
Annamaria D'urzo - I sistemi informatici SITIC SIGIS Output-CNAnnamaria D'urzo - I sistemi informatici SITIC SIGIS Output-CN
Annamaria D'urzo - I sistemi informatici SITIC SIGIS Output-CNIstituto nazionale di statistica
 
Gandhinagar institute of technology optical fiber
Gandhinagar institute of technology optical fiberGandhinagar institute of technology optical fiber
Gandhinagar institute of technology optical fibernilnildarji
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in cPrabhu Govind
 
Offshore Software Development Company
Offshore Software Development CompanyOffshore Software Development Company
Offshore Software Development Companywill123
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++Danial Mirza
 
Overview of linux kernel development
Overview of linux kernel developmentOverview of linux kernel development
Overview of linux kernel developmentPushkar Pashupat
 
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...Mangalayatan university
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Angelin R
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Linux architecture
Linux architectureLinux architecture
Linux architecturemcganesh
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c programRumman Ansari
 
Fundamental of robotic manipulator
Fundamental of robotic manipulatorFundamental of robotic manipulator
Fundamental of robotic manipulatorsnkalepvpit
 
Operator overloading and type conversions
Operator overloading and type conversionsOperator overloading and type conversions
Operator overloading and type conversionsAmogh Kalyanshetti
 

Viewers also liked (20)

Type Casting in C++
Type Casting in C++Type Casting in C++
Type Casting in C++
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
 
3 vy14lvs24
3 vy14lvs243 vy14lvs24
3 vy14lvs24
 
Annamaria D'urzo - I sistemi informatici SITIC SIGIS Output-CN
Annamaria D'urzo - I sistemi informatici SITIC SIGIS Output-CNAnnamaria D'urzo - I sistemi informatici SITIC SIGIS Output-CN
Annamaria D'urzo - I sistemi informatici SITIC SIGIS Output-CN
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
Gandhinagar institute of technology optical fiber
Gandhinagar institute of technology optical fiberGandhinagar institute of technology optical fiber
Gandhinagar institute of technology optical fiber
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
Offshore Software Development Company
Offshore Software Development CompanyOffshore Software Development Company
Offshore Software Development Company
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 
Overview of linux kernel development
Overview of linux kernel developmentOverview of linux kernel development
Overview of linux kernel development
 
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
Dynamic memory allocation(memory,allocation,memory allocatin,calloc,malloc,re...
 
Type Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLikeType Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLike
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
C for Engineers
C for EngineersC for Engineers
C for Engineers
 
Linux architecture
Linux architectureLinux architecture
Linux architecture
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Pointer in c program
Pointer in c programPointer in c program
Pointer in c program
 
Fundamental of robotic manipulator
Fundamental of robotic manipulatorFundamental of robotic manipulator
Fundamental of robotic manipulator
 
Operator overloading and type conversions
Operator overloading and type conversionsOperator overloading and type conversions
Operator overloading and type conversions
 

Similar to Typecasting in c

Computer science_xii_2016
 Computer science_xii_2016 Computer science_xii_2016
Computer science_xii_2016Ritika sahu
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++Rokonuzzaman Rony
 
L3_Tokens, Expression Evaluation.pptx
L3_Tokens, Expression Evaluation.pptxL3_Tokens, Expression Evaluation.pptx
L3_Tokens, Expression Evaluation.pptxSarowarSuman
 
2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdf2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdfTrnThBnhDng
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_castsAbed Bukhari
 
C Operators and Control Structures.pdf
C Operators and Control Structures.pdfC Operators and Control Structures.pdf
C Operators and Control Structures.pdfMaryJacob24
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants Hemantha Kulathilake
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingSherwin Banaag Sapin
 
Spf Chapter4 Variables
Spf Chapter4 VariablesSpf Chapter4 Variables
Spf Chapter4 VariablesHock Leng PUAH
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptxvijayapraba1
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxKrishanPalSingh39
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)SURBHI SAROHA
 

Similar to Typecasting in c (20)

CP Handout#3
CP Handout#3CP Handout#3
CP Handout#3
 
C PROGRAMMING p-3.pptx
C PROGRAMMING p-3.pptxC PROGRAMMING p-3.pptx
C PROGRAMMING p-3.pptx
 
Computer science_xii_2016
 Computer science_xii_2016 Computer science_xii_2016
Computer science_xii_2016
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
 
L3_Tokens, Expression Evaluation.pptx
L3_Tokens, Expression Evaluation.pptxL3_Tokens, Expression Evaluation.pptx
L3_Tokens, Expression Evaluation.pptx
 
2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdf2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdf
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
C Operators and Control Structures.pdf
C Operators and Control Structures.pdfC Operators and Control Structures.pdf
C Operators and Control Structures.pdf
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
 
representing Data in C.pptx
representing Data in C.pptxrepresenting Data in C.pptx
representing Data in C.pptx
 
Programming in Arduino (Part 1)
Programming in Arduino (Part 1)Programming in Arduino (Part 1)
Programming in Arduino (Part 1)
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
Spf Chapter4 Variables
Spf Chapter4 VariablesSpf Chapter4 Variables
Spf Chapter4 Variables
 
Fundamentals of Programming Constructs.pptx
Fundamentals of  Programming Constructs.pptxFundamentals of  Programming Constructs.pptx
Fundamentals of Programming Constructs.pptx
 
Basic of c &c++
Basic of c &c++Basic of c &c++
Basic of c &c++
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
 
Presentation 2
Presentation 2Presentation 2
Presentation 2
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 

Recently uploaded

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 

Recently uploaded (20)

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 

Typecasting in c

  • 1. Typecasting in C Typecasting is simply a mechanism by which we can change the data type of a variable, no matter how it was originally defined. When a variable is typecasted into a different type, the compiler basically treats the variable as of the new data type.
  • 2. Example: #include<stdio.h> int main(void) { int a=5,b=8; float c = 0, d = 0; c = a/b; printf("n [%f] n",c); d = (float)a/(float)b; printf("n [%f] n",d); return 0; }
  • 3. In the above example, first we divide 'a' by 'b' without typecasting. While in the second attempt we typecast both 'a' and 'b' to float and then divide them. So, what happens is, in the first attempt, the compiler knows both 'a' and 'b' are integers so it ignores the floating part of the result and stores the result of a/b in a temporary integer variable and then assign the value of this temporary integer variable to 'c'. So despite of 'c' being a float, the final value that 'c' gets is an integer ie '0' in this case. While in the second attempt, as both 'a' and 'b' are individually typecasted as 'float', so this typecasting makes compiler think as if both 'a' and 'b' are floats, so the compiler retains the floating part of the result and assigns the float value to 'c'. The output of the above program : [0.000000] [0.625000]
  • 4. CASTING DATA TYPES: Result type of arithmetic phrase depends of operand types inside it. When a phrase is consisted of various data types, result type is set by defined casting rules. Rules for casting various data types in C language are oriented to higher data type. There are two ways of casting data types in C: Implicit(automatic) casting 2. Explicit(given) casting 1.
  • 5. Implicit Casting (automatic transformation) works in a way that a variable (operand) of data type that is smaller in length (than data type of second variable) (operand), transforming internally to variable of data type with longer number length. It may sound mixed up. Example: int a; float f, g; g = a + f; // a transforms to float
  • 6. Explicit Casting (given transformation) of data types has higher priority then automatic transformation. General declaration of explicit (given) cast (cast operator): (data_type) operand Operand can be variable or phrase. Example: a = (int) c; b = (double)d + c;
  • 7. Some examples: Example 1: float a = 5.25; int b = (int)a; /*Explicit casting from float to int. The value of b here is 5*/ Example 2: char c = ’A’; int x = (int)c; /*Explicit casting from char to int. The value of x here is 65: the ASCII code of ‘A’*/
  • 8. Example 3: int x=7, y=5 ; float z; z=x/y; /*Here the value of z is 1*/ If we want to get the exact value of 7/5 then we need explicit casting from int to float: int x=7, y=5; float z; z = (float)x/(float)y; /*Here the value of z is 1.4*/ Example 4: int x=70; char c =(char)x; /*The value of c here is F: the ASCII code of 70*/