Chris Dollin said:
Nothing except that if the char*s being tested might be widely
accessible and there are any functions called between tests the
compiler can't assume that the result is unchanged.
.... unless the compiler has interprocedual (aka whole-program) optimization,
where it _can_ determine if the string won't be changed. Of course, if the
compiler is capable of that, it should also be smart enough to remove the
second (and later) calls to strlen() via CSE without having to track the
length explicitly.
I agree that compilers /can/, in principle, do this. What's not so
clear is (a) whether any of them do and (b) how widely applicable
the optimisation is.
A few do, or at least attempt to. I'm not sure this specific example is all
that helpful, but IPO and WPO can provide significant gains.
/Assuming/ that `strlen` (say) is a constant-time operation is ... sub-
optimal. (I'm not saying you're making that assumption.)
C90/99 don't say it's constant-time, so it's a flawed assumption from the
get-go. Of course, the ISO standard offers very little in the way of
performance guarantees or even guidance, so the lack of a statement isn't
all that meaningful.
S