From Newsgroup: comp.lang.c++
On 19/11/2025 20:02, Lynn McGuire wrote:
On 11/11/2025 11:23 PM, Lynn McGuire wrote:
One of these days, I will figure out what contracts are again.
Lynn
https://en.cppreference.com/w/cpp/language/contracts.html
https://www.reddit.com/r/cpp/comments/1idumqe/contracts_for_c_explained_in_5_minutes/
The actual article, rather than a forum of chatter about it:
<
https://timur.audio/contracts_explained_in_5_mins>
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p2900r14.pdf
Looks complicated.-a And is another version of assert.
Lynn
Contracts are about giving specifications to parts of code in a way that
is (or should be!) clear and consistent.
Instead of writing this :
// Pass this function a value "x", and it will calculate
// the value "y" so that y*y <= x < (y+1)*(y+1)
// Trying to find the square root of a negative number is UB.
int int_square_root(int x);
You can soon write (assuming I've got the syntax correct - C++26 is not
yet finished) :
int int_square_root(int x)
pre(x >= 0)
post(y : y * y <= x)
post(y : x < (y + 1) * (y + 1));
Now your specifications are not just comments that can be misunderstood
by the programmer, ignored by the compiler, and inconsistent with the implementation code. They are part of the code. Depending on compiler
flags or pragmas (I think this part is up to the implementation), the contracts can be ignored, checked with debug messages, trigger a handler
on failure, or cause program abort on failure. (I'd expect toolchains
to add debugger breakpoint on failure too.) And compilers will be able
to optimise on the assumption that the contracts are "true" if they pass
(or are ignored). And of course compilers can always do extra
zero-runtime checks when dealing with values known at compile time.
Yes, the contracts are somewhat like assert(). But a key feature is
that they are in the right place. Putting "assert(x >= 0)" at the start
of your "int_square_root" implementation means your perfectly correct
and debugged "int_square_root" function is bigger and slower due to
debug code, and when the assertion is triggered, your code aborts inside
the working function. Oh, and your function is no longer "pure" or
constepxr. With the "pre" contract, the check is in the right place -
at the calling site, where you might have an invalid value.
Yes, contract_assert() is a lot like assert(). But it is part of the
language rather than a macro, and that gives the language and tools a
lot more flexibility, such as how it interacts with compile-time
evaluation code, reflection, or toolchain-specific stuff.
--- Synchronet 3.21a-Linux NewsLink 1.2