for (size_t i = count; i > 0; --i) {
// use array[i - 1]
}
You can also do something like: size_t index = i - 1;
to not have to use i-1. I believe the compiler optimizes that out anyway to be identical. for (size_t i = count; i > 0; --i) {
// use array[i - 1]
}
You can also do something like: size_t index = i - 1;
to not have to use i-1. I believe the compiler optimizes that out anyway to be identical.I would do it exactly like you suggest, but using an explicitly sized type like uint32_t instead.
If I write firmware or low-level code, I almost exclusively use integers with explicit bitwidth.
One particularly famous example of a bug: https://projectzero.google/2023/01/exploiting-null-dereferen...
We usually get away with ignoring unsigned rollover because most application counts don't exceed 2**32 or 2**64. However, many can exceed these values, and in those cases, explicitly handling this case in critical systems is often better than ignoring potentially erroneous behavior.
Another concern, some people might have about this is the performance implications or what to do when you want to allow overflow. In that case you can locally disable overflow protections.