Why do many programmers use assert() function in their codes giving as its argument the answer to be outputed?
# | User | Rating |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
4 | atcoder_official | 161 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
9 | nor | 153 |
Why do many programmers use assert() function in their codes giving as its argument the answer to be outputed?
Name |
---|
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.).It doesn't worth it in ACM rules. But it's good for OI rules.
if N ≥ 1000
Yes, thanks a lot! I have corrected 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.