1

Once I saw a way in C++ to assume something, for example:

int x=7;

assume (x==7);//if not right a red error will appear and program will end.

Can someone please tell me what was the exact code for that? I have done a lot of research but found nothing since I forgot the original phrase. (I want to use this for debugging)

  • 1
    Does this answer your question? [What are assertions? and why would you use them?](https://stackoverflow.com/questions/253212/what-are-assertions-and-why-would-you-use-them) – phuclv Dec 01 '20 at 12:07
  • 1
    Herb Sutter has a nice write up comparing **assertions** and **assumptions**: [Assumptions](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p2064r0.pdf) (P2064 R0). – Eljay Dec 01 '20 at 13:01

1 Answers1

4

You are probably looking for assert, cf. https://en.cppreference.com/w/cpp/error/assert.

There is also static_assert, which does checking during compile time.

There was a proposal to add more pronounced system of "assumptions" to C++, called contracts (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1866.html), but its introduction to the language is postponed. If you are learning, you don't really need to read the document under that last URL.

lukeg
  • 4,189
  • 3
  • 19
  • 40
  • it's better to use `static_assert` in this case – phuclv Dec 01 '20 at 12:07
  • thank you, can you please take a look at: https://stackoverflow.com/questions/65092094/avl-tree-scan-nodes-by-order I don't understand the answer –  Dec 01 '20 at 14:57
  • 1
    @phuclv: `x` is not a constant expression, so cannot be used for `static_assert` – Jarod42 Dec 01 '20 at 15:11