Is strlen() calculated every time in the for statement?

Asked 2 years ago, Updated 2 years ago, 112 views

for (int i = 0; i < strlen(ss); ++i)
{
    // Hello
}

If you think about it, the ss might change inside the for statement I think strlen(ss) should be calculated every time

But if you do strlen() every time, the speed decreases, so the compiler can just replace it with a fixed value...??

How is this code optimized? Will it be different depending on the situation?

gcc c++ c optimization strlen

2022-09-21 15:37

1 Answers

As you said, strlen() is recalculated for each iteration statement because the string length may change in the middle.

In some cases, the compiler automatically optimizes if the ss does not change in the for statement It's better to code yourself than to trust the compiler

Personally, if the ss length is fixed, I write this code.

for (int i = 0, n = strlen(ss); i < n; ++i)
//or
for (int i = 0; ss[i]; ++i)


2022-09-21 15:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.