What is lost in this example from the basic principles of Cpp?

What wasted in the example from the Cpp Core Guide?

Page 9: Do not waste time and space

[...]

void lower(zstring s) { for (int i = 0; i < strlen(s); ++i) s[i] = tolower(s[i]); } 

Yes, this is an example from production code. We leave the reader to understand what was wasted.

from https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rp-waste

+11
c ++ cpp-core-guidelines
source share
5 answers

strlen is evaluated at each iteration of the loop.

+24
source share

strlen is called every time a loop condition is checked, and takes O (n) time to call, so the total loop time is O (n ^ 2).

+9
source share

A lot of time is wasted, and a segmentation error can occur as the author of the code incrementing s , and not i in the loop:

 for (int i = 0; i < strlen(s); ++s) //right here ^^^^ 
+7
source share

As other participants have already pointed out, strlen(s) is called several times because it is in a condition, implying that it must be cached and reused.

But strlen(s) doesn't have to be called at all! s is (or implicitly converted) to a nul-terminated char array, since this is what strlen expects. Therefore, we can simply use this property for our own cycle.

 void lower(zstring s) { for (char *p = s; *p; ++p) *p = std::tolower((unsigned char)*p); } 
+5
source share

If the zstring class zstring not have any very unintuitive semantics, the function in its current form is a waste of time space and , since its "result" cannot be used after the function, it is passed as a value and not returned.

Therefore, in order not to waste time on the useless calculation of lowercase letters that cannot be used, as well as space when copying the passed parameter, I would pass a link!

0
source share

All Articles