A type conversion is a conversion between types. For example;
Code:
int main()
{
char x;
int i;
x = 'a';
i = x; /* Implicitly convert x to int, and assign the result to i */
}
A cast is used to make the conversion explicit. So the above could be done using a cast.
Code:
int main()
{
char x;
int i;
x = 'a';
i = (int)x; /* Explicitly convert x to int, assign the result to i */
}
In some cases, a conversion is technically possible but disallowed under the rules of the language. For example;
Code:
int main()
{
char ax[2];
char *px;
int *pi;
px = ax; /* Implicitly convert ax into a pointer to char */
pi = px; /* Attempt to implicitly convert px from a pointer to char into a pointer to int */
*pi = 42;
}
This code will yield a compiler error on the commented line because an implicit conversion between pointer types (unless one is void) is disallowed. The compiler can be bludgeoned into submission, so it allows the conversion, by using a cast.
Code:
int main()
{
char ax[2];
char *px;
int *pi;
px = ax; /* Implicitly convert ax into a pointer to char */
pi = (int *)px; /* Explicitly convert px from a pointer to char into a pointer to int */
*pi = 42;
}
This code will now compile, but the line "*pi = 42;" now yields undefined behaviour (among other things, that is the reason the implicit conversion is disallowed).