5 Typecasting
5 Typecasting
Conversion
int x=1, z;
float y=2.3,
z =x+y;
z=x+y; //z=3
int+float=float
int+int=int
float/int =float
int/float=float
C-Typecasting / Type
Conversion
Definition:
Typecasting is converting one data type into another one. It is
also called as data conversion or type conversion.
long double
double
float
long int
Int
Short int
char
• Implicit typecasting: Promotion and Demotion
Promotion Demotion
1. #include <stdio.h> 1. #include <stdio.h>
2. int main() 2. int main()
3. { 3. {
4. printf("Hello World\n"); 4. printf("Hello World\n");
5. int a=10; 5. int a;
6. float c; 6. float c=10.23;
7. c=a; //float=int 7. a=c; //int=float
8. printf("a=%d, \t c=%f",a,c); 8. printf("a=%d, \t c=%f",a,c);
9. return 0; 9. return 0;
10.} 10.}
Output: Output:
Hello World Hello World
a=10 c=10.000000 a= 10 c=10.23
• Important points about implicit typecasting
{ {
int a; int a;
short b; short b;
b=65535; //max value short can hold a=65537; //a value 1 more that max value short can hold
a=b; 32 bits=(15bits 0)(1 bit 1)(16 bits 0)00000….1000…0001
printf(“a=%d”, a); b=a;
} printf(“b=%d”, b);
}
Here,
•The type name is the standard 'C' language data type.
•An expression can be a constant, a variable or an actual expression
• Explicit typecasting
1. #include<stdio.h> Output:
2. int main()
3. {
4. float a = 3.2;
5. int b = a; //warning
6. int b = (int)a + 1;
7. printf("Value of a is %f\n",
a);
8. printf("Value of b is %d\
n",b);
9. return 0;
10.}
1.We have initialized a variable 'a' of type float.
• Explicit typecasting 2.Next, we have another variable 'b' of integer
data type. Since the variable 'a' and 'b' are of
1. #include<stdio.h> different data types, 'C' won't allow the use of
2. int main() such expression and it will raise an error. In some
versions of 'C,' the expression will be evaluated
3. { but the result will not be desired.
4. float a = 1.2; 3.To avoid such situations, we have typecast the
variable 'a' of type float. By using explicit type
5. //int b = a; //warning or error casting methods, we have successfully converted
float into data type integer.
6. int b = (int)a + 1; 4.We have printed value of 'a' which is still a float
7. printf("Value of a is %f\n", 5.After typecasting, the result will always be an
integer 'b.'
a);
8. printf("Value of b is %d\
n",b); Output:
9. return 0;
10.}
Explicit typecasting - Example
int a=5, b=2;
float c;
Statements Output
(i) c=a/b; int/int=int c = 2.000000
(ii)c= (float)a/b; c=
float/int=float 2.5
(iii)c=(float)(a/b) c =2.000000
(float)(5/2)
(float) (2)
(iv)c=a/(float)b c =2.5
int/float = float