3 ms·
Well, when you are not in doubt you don't want unnecessary bounds checks.
by pptr 3y ago
Well, when you are not in doubt you don't want unnecessary bounds checks.
- estebank 3y agoIf you can communicate to a human that a bounds check isn't necessary, you can communicate it to a compiler.
- pptr 3y agoI'm all for better tools to help the compiler figure things out. Here is an example where I can't communicate the invariants to the compiler: ``` std::vector<int> v; ... v.push_back(2); std::sort(v.begin(), v.end()); // no need to check i < size because we know we will find value 2 somewhere in the v. for (int i = 0; i < v.size(); ++i) { if (v[i] == 2) return i; } ``` Note that in C++ you can manually mark code after the loop as unreachable, which would indeed skip the size check. But that's as bad as not checking bounds in the first place.
- soulbadguy 3y agoNo...