• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 // Copyright (C) 2008-2018 Lorenzo Caminiti
3 // Distributed under the Boost Software License, Version 1.0 (see accompanying
4 // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
5 // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html
6 
7 //[n1962_factorial
8 #include <boost/contract.hpp>
9 #include <cassert>
10 
factorial(int n)11 int factorial(int n) {
12     int result;
13     boost::contract::check c = boost::contract::function()
14         .precondition([&] {
15             BOOST_CONTRACT_ASSERT(n >= 0); // Non-negative natural number.
16             BOOST_CONTRACT_ASSERT(n <= 12); // Max function input.
17         })
18         .postcondition([&] {
19             BOOST_CONTRACT_ASSERT(result >= 1);
20             if(n < 2) { // Select assertion.
21                 BOOST_CONTRACT_ASSERT(result == 1);
22             } else {
23                 // Assertions automatically disabled in other assertions.
24                 // Therefore, this postcondition can recursively call the
25                 // function without causing infinite recursion.
26                 BOOST_CONTRACT_ASSERT_AUDIT(n * factorial(n - 1));
27             }
28         })
29     ;
30 
31     return n < 2 ? (result = 1) : (result = n * factorial(n - 1));
32 }
33 
main()34 int main() {
35     assert(factorial(4) == 24);
36     return 0;
37 }
38 //]
39 
40