code_fille's blog

By code_fille, 9 years ago, In English

Why do many programmers use assert() function in their codes giving as its argument the answer to be outputed?

  • Vote: I like it
  • +6
  • Vote: I do not like it

»
9 years ago, # |
Rev. 3   Vote: I like it +22 Vote: I do not like it

Some judging systems provide full report of a submitted solution with the error codes the program returned. That why several coders use the following trick:

Let's assume you submitted code on ACM rules and got WA. In some situations with the input consisting of few numbers it is possible to find out such test. You only need to estimate amount of "interesting" tests and assert them.

E.g., if you asked to find all the numbers generated by permutating 1 and 0 in binary form of given N. If you failed Test #6, you can do assert(N>=1000) and it will cause RE if N<1000. So you can get N from the test using K times binary search (N>500&&N<1000, N>250&&N<500 and etc.).

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +10 Vote: I do not like it

    It doesn't worth it in ACM rules. But it's good for OI rules.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +16 Vote: I do not like it

    assert(N<1000) and it will cause RE if N<1000

    if N ≥ 1000

»
9 years ago, # |
  Vote: I like it +23 Vote: I do not like it

In short: because it's a good way of continuous local testing. They give you additional way of checking your program, and this doesn't even need your assistance after writing — your program checks its invariants during each run.

Say, you have some invariant in your code, which is essential for further work and it's easy to test. But sometimes, when it is not provided, answer is still correct. That's totally uncool, if you want to find all bugs. If you check this invariant with assertion, you will see that it is broken even if the answer on this particular test would be correct.

Another usecase: imagine that you have some data structure in your code. To be sure that it works correctly, you can add another implementation (say, O(n2)) and check with assertions that answers that both of these implementations provide are similar (locally only, of course). That way, if you get wrong answer locally, you know that it is not because of your data structures. And, similarly, if assertion fails inside of them, you know that something is definitely wrong.

History from KOTEHOK: one day he was participating in Google Code Jam. He successfully submitted small input and downloaded large input. Some assertion failed during run on large input. He rushed into his code and managed to locate a bug, fix it and submit correct answers. So, if it wasn't for assertions, he would be unable to understand that answers are wrong.