Software Contracts, Part 7: Contracts as annotations - language features used to express contracts

My last post on contracts introduced the idea that a languages type system can be used as a mechanism to expose the contract of a function.  It turns out that language designers started recognising this fact and they started adding annotations to types that allow the contract for functions to be expressed.

As is to be expected, originally these annotations were relatively limited in scope - for instance, the C language added a concept of "type qualifier" when it was standardized (K&R had no such concept).  They only added a couple of simple qualifiers - const and volatile.  When a parameter to a function was declared to be "const", it meant that the function's contract included a guarantee not to modify the parameter [1]. 

Of course, sometimes it was rather hard to decypher the difference between "const char *" and "char *const" (the first is a pointer to a constant character, the second is a constant pointer to a character), but the intent was there.  The C language specification treated the type qualifier mostly as a hint - it didn't do a particularly good job of enforcing them.

 

For C++, the language designers went further than in C. They tightened up the semantics for "const" adding stricter type checks.  And they added new parameter type, a "reference" parameter.  When a function took a reference to a variable as a parameter, it essentially says "the contract for this function includes the ability to modify the contents of this variable".

 

 

Next:  Contract Annotations enforced outside the compiler.

[1] Yeah, I know about CreateProcess.

Edit: Ok, I screwed up the definitions of const char * and char * const.