in short, typecasting and type conversion are designed to convert a variable from one datatype to other
Type conversion
in the first place, type conversion can be done by implicitly and it is used, if the two-variable have a different datatype
Implicit
to clarify, implicit conversion mean’s the data types are automatically adjusted by a compiler from the hierarchy of datatypes and The data types are adjusted from lower-level order to higher-level order of data types
If int a=2 and float b=2.5 then find a x b;
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=2;
float b=2.5;
printf("c=%d",a*b);
return 0;
}
Output
error : warning format '%d' expects argument of 'int' but argument 2 has type 'double'
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=2;
float b=2.5;
printf("c=%f",a*b);
return 0;
}
Output
5.000000
Typecasting
typecasting in contrast, achieved by explicitly. that is to say, forcefully conversion
in fact, the above problem of type conversion(automatic conversion by the compiler) can be avoided by using Typecasting
Syntax
(data type) expression;
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=2;
float b=2.5;
int c = (int)a*b;
printf("c=%d",c);
return 0;
}
Output
c=5
Leave a Reply