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

后端 未结 18 1700
再見小時候
再見小時候 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 16:04

    Arrgh, it will, even under ideal circumstances, dammit!

    As of today (January 2018), and gcc 7.3 and clang 5.0, if you compile:

    #include 
    
    void bar(char c);
    
    void foo(const char* __restrict__ ss) 
    {
        for (int i = 0; i < strlen(ss); ++i) 
        {
            bar(*ss);
        }
    }    
    

    So, we have:

    • ss is a constant pointer.
    • ss is marked __restrict__
    • The loop body cannot in any way touch the memory pointed to by ss (well, unless it violates the __restrict__).

    and still, both compilers execute strlen() every single iteration of that loop. Amazing.

    This also means the allusions/wishful thinking of @Praetorian and @JaredPar doesn't pan out.

提交回复
热议问题