loop.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Copyright (C) 2008-2018 Lorenzo Caminiti
  2. // Distributed under the Boost Software License, Version 1.0 (see accompanying
  3. // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
  4. // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html
  5. #include <boost/contract.hpp>
  6. #include <vector>
  7. #include <algorithm>
  8. #include <limits>
  9. int main() {
  10. std::vector<int> v;
  11. v.push_back(1);
  12. v.push_back(2);
  13. v.push_back(3);
  14. //[loop
  15. int total = 0;
  16. // Contract for a for-loop (same for while- and all other loops).
  17. for(std::vector<int>::const_iterator i = v.begin(); i != v.end(); ++i) {
  18. boost::contract::old_ptr<int> old_total = BOOST_CONTRACT_OLDOF(total);
  19. boost::contract::check c = boost::contract::function()
  20. .precondition([&] {
  21. BOOST_CONTRACT_ASSERT(
  22. total < std::numeric_limits<int>::max() - *i);
  23. })
  24. .postcondition([&] {
  25. BOOST_CONTRACT_ASSERT(total == *old_total + *i);
  26. })
  27. ;
  28. total += *i; // For-loop body.
  29. }
  30. //]
  31. assert(total == 6);
  32. return 0;
  33. }