C gives us two types of casting: Implicit casting — happens automatically in expressions and function calls, and Explicit casting — with the cast operator (T) v (e.g. (int) x).
Both are powerful - and both introduce risks - making subtle, hard-to-detect bugs easy to introduce.
I've been looking for safer way to use casts in C, and I came up with simple idea: replace (T) v with function like macros, similar in spirit to SQL's CONVERT(type, value).
A Small Example (same behavior, better readability):
// before, It it:
// (*((long *) buf)) + 1 OR
// *((long *) (buf + 1 )) OR
// *(((long *) buf) + 1)
long p = *(long *) buf + 1;
/* after */
long p = *CAST_PTR1(long *, buf) + 1;
Full Article (Medium - no paywall):
Safer Casting in C — With Zero Runtime Cost
I tried a simple approach: replace (T)v with function-like macros such as CAST_VAL, CAST_PTR, and CAST_PTR1, and UNCONST. The idea isn’t to make C type-safe, but to make casts explicit, structured, and easier to audit. Some basic checks can be enforced at compile time (using gcc/clang extensions), and everything still compiles down to the same code — no runtime cost.
In practice, this shifts casts from “hidden syntax” to something more visible and intentional. For example, separating value casts from pointer casts, and explicitly handling things like removing const, makes questionable conversions stand out immediately in code review.
Curious if others have tried something similar, or if you rely mostly on compiler warnings (-Wconversion, -Wcast-*) and static analysis for this. Does this feel useful, or just adding noise on top of C’s existing model?
Top comments (0)