10 ms·
Using asserts AND keeping them in production builds. This really helps whipping people into shape and making them pay attention to what they write. Also helps
by huhtenberg 6y ago
Using asserts AND keeping them in production builds.
This really helps whipping people into shape and making them pay attention to what they write. Also helps documenting the code in a very succinct way.
- okl 6y agoAnd in terms of performance it costs next to nothing. Just don't put them into your critical loops. You can also print backtraces when an assertion fails: https://stackoverflow.com/questions/77005/how-to-automatically-generate-a-stacktrace-when-my-program-crashes https://stackoverflow.com/questions/77005/how-to-automatical...
- Someone 6y agoDepends on what’s in your asserts. If, for example, you check validity of your custom data structure in an assert, even a single assert can cost a lot to more than nothing. (Whether you should use assert for that kind of checks that probably only should run in tests is debatable, but it sometimes happens)
- parenthesis 6y agoWhat really costs nothing is putting assert(0) in any place that should be unreachable. For example: switch (...) { case A: ... case B: ... ... default: // all possible cases are dealt with above assert(0); }
- identity0 6y agoOne ugly trick for unreachable branches is this: assert(!"You gave an invalid letter"); The string literal is a pointer, so !pointer is false. And then you get a nice explanation message when the assertion fails. I wish all assert gave optional explanation messages.
- saagarjha 6y agoI often do assert(condition && "String explanation") myself.
- longcommonname 6y agoFor anyone following along. Don't do this if the code base is already hotshit. This will only make things worse and not prevent errors, just cause more outages.