int Successor(int x) { return x + 1; }
Because that is undefined behavior for x == INT_MAX, and if the compiler is detecting undefined behavior and emitting errors, this would be an obvious candidate.How about this simple function?
int Divide(int x, int y) { return x / y; }
This is undefined behavior for y == 0, or for x == -INT_MAX - 1 and y == -1. Shall it produce an error?(Never mind why you're writing such simple functions. Imagine they do something more complex and just do the division or addition or whatever as part of their work.)
Here's a fun one:
void StrClear(char *str) {
memset(str, 0, strlen(str));
}
This will invoke undefined behavior if passed a string constant as its parameter, or if passed an array that doesn't have a 0 in it. There is no portable (i.e. without invoking undefined behavior) way to check whether the parameter is a string constant or doesn't have a 0, so it is impossible to assert away the undefined behavior for this.Many real, practical, production-worthy C functions will invoke undefined behavior with some inputs. Turning undefined behavior into a compile-time error will cause virtually all C code to not compile.
Well, the compiler should warn you if you try to pass a (char const *) to a function expecting a (char *). Use -Wwrite-strings to make string literals have type (char const[]) rather than (char[]).
The simple answer is "the halting problem".
If you can build a compiler that knows with certainty what runtime behavior would result from any program (including whether undefined behavior occurs), then you could solve the halting problem, but the halting problem is provably undecidable. So such a compiler cannot exist even in theory for the general case.
Yes, you can template-match a bunch of special cases, but the user can always write new code that doesn't match any of your "known to be defined behavior" patterns but still executes only defined behavior. Guaranteed!