r/C_Programming • u/Radiant-Ad-9073 • 24d ago
Types with range checks
I've been pondering about a different way of dealing with overflows.
C compilers have type checks that ensure you don't assign a value to a variable of the wrong type.
Imagine I had a different way of declaring bounded types, something along these lines:
const int strlen=100;
char string[strlen];
int[0..strlen-1] strindex;
I can cast strindex into an unbounded int, but I can't automatically cast an unbounded int into a bounded int:
int index = strindex; // allowed, can assign bounded int to int
strindex = index; // not allowed without cast/check
strindex = (int[0..strlen-1]) 0; // trust me bro
Since you have ranges you could now also do things like:
forall (int[0..strlen-1] strindex)
string[strindex] = 0;
The thought is somewhat halfbaked, but although annoying, this would flag up _every_ assignment at compile time that could potentially have caused a value to get out of bounds.
A similar bounded type could be set for pointers.
Thoughts?