Will strlen be calculated multiple times if used in a loop condition?

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

for (int i = 0, n = strlen(ss); i < n; ++i)

or possibly

for (int i = 0; ss[i]; ++i)

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)