Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

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

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 functions aren't actually a part of the language itself, neither are they defined in math.h (only declared), will the constant ones get precalculated at compile time, or will they be wastefully calculated at runtime?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 <math.h>

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...