Due to a recent topic on (un)definedness pre/postfix increment behaviour, I was hoping for a quick check on this:
1 2 3 4
// Check if either t.i or t.j is in array.
for (ix = 0; ix < maxtb; ++ix) {
if (t.i == *to || t.j == *to++) break;
}
It looks legal to me at first sight [postfix generally isn't the one causing problems anyway] but I'd like some certainty. As always, all nice alternatives are also welcome.
It's technically fine, although I'd consider it somewhat questionable style.
If a variable is used several times before it is incremented, it should happen on a separate line at the end. That's more obvious and keeps you from pushing the increment around when you change the code.
If to is known to be a pointer or random access iterator, the following might be preferable:
1 2 3
for (ix = 0; ix < maxtb; ++ix) {
if (t.i == to[ix] || t.j == to[ix]) break;
}
If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression.
Your code example was the original version I had. The thing is that I'll be continuing with the object, if found. Rather than having to dereference it at every use, having a direct pointer would save me some effort (for ease of use I'd probably have to get a pointer to to[ix] anyway). Doubly so because I intend to reuse 'ix' several times in the same scope (and yes, the value matters), while *to will be constant from that point on.
That seemed like a bug to me, although it only matters when to is used afterwards. to points to the matching element if it was t.i, but to the one after it if it was t.j? Probably unintended.
Rather than having to dereference it at every use, having a direct pointer would save me some effort
Well, there are references for that. But it doesn't really matter, either variant works.
I'm wondering if it's true though. I know C++ uses lazy evaluation and stops evaluating conditionals when it finds its first 0 (in AND) or 1 (in OR). However, does it also skip arithmetic operations embedded in further conditionals? That seems like a major source of unintended behaviour.