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

后端 未结 18 1735
再見小時候
再見小時候 2020-12-07 15:10

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
}
<         


        
18条回答
  •  醉酒成梦
    2020-12-07 15:47

    The predicate code in it's entirety will be executed on every iteration of the for loop. In order to memoize the result of the strlen(ss) call the compiler would need to know that at least

    1. The function strlen was side effect free
    2. The memory pointed to by ss doesn't change for the duration of the loop

    The compiler doesn't know either of these things and hence can't safely memoize the result of the first call

提交回复
热议问题