Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 981
daisy Avatar asked Jul 06 '12 15:07

daisy


People also ask

What is the time complexity of strlen?

The time complexity of standard strlen is O(n). Since all trailing characters are '\0', we can use binary search. By comparing middle two elements with '\0', we can decide whether we need to recur for left half or right half. IF one of them is \0, then we found the first occurrence.

Can strlen fail?

Ok, I need to add some explanation. My application is getting a string from a shared memory (which is of some length), therefore it could be represented as an array of characters. If there is a bug in the library writing this string, then the string would not be zero terminated, and the strlen could fail.

What can I use instead of strlen?

If you're using a char[] , then you can use sizeof(str) - 1 instead.

Can we use strlen with string?

For C++ strings, there's no reason to use strlen . Just use string::length : Clarity: The length() (or size() ) member functions unambiguously give back the length of the string.


1 Answers

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.

like image 180
Mike Seymour Avatar answered Sep 22 '22 06:09

Mike Seymour