Casting#
Casts are written as (T)expr. Avoid casts where the language
would convert implicitly; casts are reserved for genuinely
changing representation.
Truncating a double to int.
double d = 3.7;
int i = (int)d; /* 3 (truncates) */
Casting through void *.
void *vp = malloc(16);
char *cp = (char*)vp; /* explicit cast from void* */
Implicit integer promotions (the integer promotions and usual arithmetic conversions) silently widen and re-sign; the operator reads them carefully.
unsigned char a = 250;
signed char b = -10;
if (a + b > 0) { /* a and b promote to int before adding */ }
References#
Primitives for the integer types affected by promotion.
Pointers for
void *and the(T*)cast form.