In C, certain types of casts are well-defined and do not invoke undefined behavior (UB) under the strict aliasing rules or other parts of the C standard. Below is a list of well-defined casts, categorized for clarity:
1. Casts Between Arithmetic Types
Casts between arithmetic types (including int, float, double, char, enum, etc.) are well-defined:
int i = 42;
float f = (float)i; // Well-defined
char c = (char)i; // Well-defined
2. Casts to and from void *
Casting any object pointer to void * and back to its original type is well-defined:
int i = 42;
void *p = &i; // Well-defined
int *q = (int *)p; // Well-defined
3. Casts Between Pointer Types in the Same Hierarchy
Casts between pointers to compatible types (e.g., pointers to the same struct or union, or pointers to the same array type) are well-defined:
typedef struct { int x; } S;
S *s;
S *t = (S *)s; // Well-defined
4. Casts to and from char or unsigned char (or _Bool)
Accessing any object through a char *, unsigned char *, or _Bool * is well-defined, as these types are exempt from the strict aliasing rule:
int i = 42;
unsigned char *p = (unsigned char *)&i; // Well-defined
5. Function Pointer Casts
Casts between function pointers and void (*)() (or other compatible function types) are well-defined, though calling a function through an incompatible pointer type is UB:
void (*fp)(void);
int (*ip)(int);
fp = (void (*)(void))ip; // Well-defined (but calling fp is UB if ip expects an argument)
6. Casts Involving intptr_t and uintptr_t
Casts between pointers and fixed-width integer types (intptr_t or uintptr_t) are well-defined in C99 and later:
#include <stdint.h>
int i = 42;
uintptr_t p = (uintptr_t)&i; // Well-defined
7. Casts to nullptr (C++ only, but analogous in C)