Do math functions of constant expressions get pre-calculated at compile time?

后端 未结 6 1109
感动是毒
感动是毒 2020-12-06 17:10

I tend to use math functions of constant expressions for convinience and coherence (i.e log(x)/log(2) instead of log(x)/0.3...). Since these functi

6条回答
  •  萌比男神i
    2020-12-06 17:33

    It depends on the compiler and the optimization flags. As @AndrewyT points out, GCC has the ability to specify which functions are constant and pure via attributes, and in this case the answer is positive, it will inline the result, as you can easily check:

    $ cat constant_call_opt.c 
    #include 
    
    float foo() {
            return log(2);
    }
    
    $ gcc -c constant_call_opt.c -S
    
    $ cat constant_call_opt.s 
            .file   "constant_call_opt.c"
            .text
    .globl foo
            .type   foo, @function
    foo:
            pushl   %ebp
            movl    %esp, %ebp
            subl    $4, %esp
            movl    $0x3f317218, %eax
            movl    %eax, -4(%ebp)
            flds    -4(%ebp)
            leave
            ret
            .size   foo, .-foo
            .ident  "GCC: (Ubuntu 4.3.3-5ubuntu4) 4.3.3"
            .section        .note.GNU-stack,"",@progbits
    

    no function call there, just loads a constant (0x3f317218 == 0.69314718246459961 == log(2))

    Althought I have not any other compiler at hand to try now, I think you could expect the same behaviour in all the major C compilers out there, as it's a trivial optimization.

提交回复
热议问题