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

后端 未结 18 1726
再見小時候
再見小時候 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:09

    well, I noticed that someone is saying that it is optimized by default by any "clever" modern compiler. By the way look at results without optimization. I tried:
    Minimal C code:

    #include 
    #include 
    
    int main()
    {
     char *s="aaaa";
    
     for (int i=0; i

    My compiler: g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
    Command for generation of assembly code: g++ -S -masm=intel test.cpp

    Gotten assembly code at the output:
        ...
        L3:
    mov DWORD PTR [esp], 97
    call    putchar
    add DWORD PTR [esp+40], 1
        .L2:
         THIS LOOP IS HERE
        **mov    ebx, DWORD PTR [esp+40]
    mov eax, DWORD PTR [esp+44]
    mov DWORD PTR [esp+28], -1
    mov edx, eax
    mov eax, 0
    mov ecx, DWORD PTR [esp+28]
    mov edi, edx
    repnz scasb**
         AS YOU CAN SEE it's done every time
    mov eax, ecx
    not eax
    sub eax, 1
    cmp ebx, eax
    setb    al
    test    al, al
    jne .L3
    mov eax, 0
         .....
    

提交回复
热议问题