I’m not sure if the following code can cause redundant calculations, or is it compiler-specific?
for (int i = 0; i < strlen(ss); ++i)
{
// blabla
}
Will strlen() be calculated every time when i increases?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes,
strlen()will be evaluated on each iteration. It’s possible that, under ideal circumstances, the optimiser might be able to deduce that the value won’t change, but I personally wouldn’t rely on that.I’d do something like
or possibly
as long as the string isn’t going to change length during the iteration. If it might, then you’ll need to either call
strlen()each time, or handle it through more complicated logic.