Whatever you might mean - this is not one of these cases....and it's not exactly a good habit, not in cases such as this. Also, when you want to explicitly tell the reader that a cast is performed, you should use static_cast and not the "hamfist cast" operator. |
Don't be so short-sighted with only "this case". If "this case" is the only thing you're interested in, you don't even need the static_cast stuff and it will work to compare a variable of size_t and int. Developing good habits starts from "this case" but is never confined to "this case". However, I do agree static_cast shall be used --- only because this is a C++ forum. With a C background, I prefer c style cast and I reserve my personal preference.
it's fairly safe to assume the compiler will retrieve the size just one single time and store it in a register |
No. "it's safe to assume ..." This is never going to be the last time I see this one. Loop hoisting is not a born gift with C++/C. There're numerous old versions of compilers from various vendors (particularly in 90s) that don't support loop hoisting and are still in use. However, loop hoisting is a job of RECENT compilers. Since we are not given the compiler information, don't make insecure assumptions. What's more, even for these days, operations like left/right shift are not supported in terms of loop hoisting for a wide range of compilers. So don't assume before you really know.
I know this is not so closely related, but do you know why there's so much code injection these days? Insecure assumptions! Remember, they can be dangerous.
calling size() will usually translate in a single mov instruction (on x86) |
Not sure what you mean, but a single mov instruction only copies some value into a register. It alone doesn't give you the result of size(). Maybe you really want to say "one more mov instruction"? --- given your "safe to assume", yes, you're right. But if your assumption is not that "safe", then extra cost of time complexity O(n) occurs.
vector<int>& column = states[i]; |
This is not as good. There're a few differences between pointers and references. In one word, pointers are more powerful and more flexible than references. For example, a reference cannot be used to reference another object after initialization while pointers can; a reference cannot be null while pointers can ... I'm sure you can find a lot of text books on this topic. Although those standard makers add reference into C++, it is a controversial feature because reference syntactically obscures identifier's indirection, which syntactically confuses yourself whether you're dealing with a variable or a "pointer"(worse readability). Again, for the sake of good programming habits, avoid it if you have more powerful (and syntactically clearer) tools like pointers.