Posts

Showing posts from January 14, 2019

Enforcing function contract at compile time when possible

Image
13 8 (this question was inspired by How can I generate a compilation error to prevent certain VALUE (not type) to go into the function?) Let's say, we have a single-argument foo , semantically defined as int foo(int arg) { int* parg; if (arg != 5) { parg = &arg; } return *parg; } The whole code above is used to illustrate a simple idea - function returns it's own argument unless the argument is equal to 5, in which case behavior is undefined. Now, the challenge - modify the function in such a way, that if it's argument is known at compile time, a compiler diagnostic (warning or error) should be generated, and if not, behavior remains undefined in runtime. Solution could be compiler-dependent, as long as it is available in either one of the big 4 compilers. H...