Inline version of a function returns different value than non-inline version The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceIs floating point math broken?IEEE-754 floating-point precision: How much error is allowed?Benefits of inline functions in C++?When should I write the keyword 'inline' for a function/method?The meaning of static in C++setw within a function to return an ostreamstd::atomic_is_lock_free(shared_ptr<T>*) didn't compileWhy doesn't the istringstream eof flag become true when successfully converting a boolean string value to a bool?How to implement StringBuilder class which to be able to accept IO manipulatorsFunction overloading with different return typesProblems benchmarking simple code with googlebenchmarkC++ - Odd Reciprocal Inequivalence

Does Parliament need to approve the new Brexit delay to 31 October 2019?

Sort a list of pairs representing an acyclic, partial automorphism

Match Roman Numerals

Who or what is the being for whom Being is a question for Heidegger?

Is it ethical to upload a automatically generated paper to a non peer-reviewed site as part of a larger research?

I could not break this equation. Please help me

Can undead you have reanimated wait inside a portable hole?

What is special about square numbers here?

Relations between two reciprocal partial derivatives?

How can I define good in a religion that claims no moral authority?

Did God make two great lights or did He make the great light two?

How is simplicity better than precision and clarity in prose?

Do warforged have souls?

Is there a writing software that you can sort scenes like slides in PowerPoint?

First use of “packing” as in carrying a gun

Can a novice safely splice in wire to lengthen 5V charging cable?

system() function string length limit

University's motivation for having tenure-track positions

How did passengers keep warm on sail ships?

Problems with Ubuntu mount /tmp

Make it rain characters

The following signatures were invalid: EXPKEYSIG 1397BC53640DB551

Derivation tree not rendering

Did the UK government pay "millions and millions of dollars" to try to snag Julian Assange?



Inline version of a function returns different value than non-inline version



The 2019 Stack Overflow Developer Survey Results Are In
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceIs floating point math broken?IEEE-754 floating-point precision: How much error is allowed?Benefits of inline functions in C++?When should I write the keyword 'inline' for a function/method?The meaning of static in C++setw within a function to return an ostreamstd::atomic_is_lock_free(shared_ptr<T>*) didn't compileWhy doesn't the istringstream eof flag become true when successfully converting a boolean string value to a bool?How to implement StringBuilder class which to be able to accept IO manipulatorsFunction overloading with different return typesProblems benchmarking simple code with googlebenchmarkC++ - Odd Reciprocal Inequivalence



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








66















How can two versions of the same function, differing only in one being inline and the other one not, return different values? Here is some code I wrote today and I am not sure how it works.



#include <cmath>
#include <iostream>

bool is_cube(double r)

return floor(cbrt(r)) == cbrt(r);


bool inline is_cube_inline(double r)

return floor(cbrt(r)) == cbrt(r);


int main()

std::cout << (floor(cbrt(27.0)) == cbrt(27.0)) << std::endl;
std::cout << (is_cube(27.0)) << std::endl;
std::cout << (is_cube_inline(27.0)) << std::endl;




I would expect all outputs to be equal to 1, but it actually outputs this (g++ 8.3.1, no flags):



1
0
1


instead of



1
1
1


Edit: clang++ 7.0.0 outputs this:



0
0
0


and g++ -Ofast this:



1
1
1









share|improve this question









New contributor




zbrojny120 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 3





    Can you please provide what compiler, compiler options are you using and what machine ? Works ok for me on GCC 7.1 on Windows.

    – Diodacus
    Apr 9 at 10:13






  • 29





    Isn't == always a bit unpredictable with floating point values?

    – 500 - Internal Server Error
    Apr 9 at 10:15






  • 3





    related stackoverflow.com/questions/588004/…

    – user463035818
    Apr 9 at 10:16






  • 2





    Did you set the -Ofast option, which allows such optimizations?

    – cmdLP
    Apr 9 at 10:18






  • 4





    Compiler returns for cbrt(27.0) the value of 0x0000000000000840 while the standard library returns 0x0100000000000840. The doubles differ in 16th number after comma. My system: archlinux4.20 x64 gcc8.2.1 glibc2.28 Checked with this. Wonder if gcc or glibc is right.

    – Kamil Cuk
    Apr 9 at 10:59


















66















How can two versions of the same function, differing only in one being inline and the other one not, return different values? Here is some code I wrote today and I am not sure how it works.



#include <cmath>
#include <iostream>

bool is_cube(double r)

return floor(cbrt(r)) == cbrt(r);


bool inline is_cube_inline(double r)

return floor(cbrt(r)) == cbrt(r);


int main()

std::cout << (floor(cbrt(27.0)) == cbrt(27.0)) << std::endl;
std::cout << (is_cube(27.0)) << std::endl;
std::cout << (is_cube_inline(27.0)) << std::endl;




I would expect all outputs to be equal to 1, but it actually outputs this (g++ 8.3.1, no flags):



1
0
1


instead of



1
1
1


Edit: clang++ 7.0.0 outputs this:



0
0
0


and g++ -Ofast this:



1
1
1









share|improve this question









New contributor




zbrojny120 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 3





    Can you please provide what compiler, compiler options are you using and what machine ? Works ok for me on GCC 7.1 on Windows.

    – Diodacus
    Apr 9 at 10:13






  • 29





    Isn't == always a bit unpredictable with floating point values?

    – 500 - Internal Server Error
    Apr 9 at 10:15






  • 3





    related stackoverflow.com/questions/588004/…

    – user463035818
    Apr 9 at 10:16






  • 2





    Did you set the -Ofast option, which allows such optimizations?

    – cmdLP
    Apr 9 at 10:18






  • 4





    Compiler returns for cbrt(27.0) the value of 0x0000000000000840 while the standard library returns 0x0100000000000840. The doubles differ in 16th number after comma. My system: archlinux4.20 x64 gcc8.2.1 glibc2.28 Checked with this. Wonder if gcc or glibc is right.

    – Kamil Cuk
    Apr 9 at 10:59














66












66








66


9






How can two versions of the same function, differing only in one being inline and the other one not, return different values? Here is some code I wrote today and I am not sure how it works.



#include <cmath>
#include <iostream>

bool is_cube(double r)

return floor(cbrt(r)) == cbrt(r);


bool inline is_cube_inline(double r)

return floor(cbrt(r)) == cbrt(r);


int main()

std::cout << (floor(cbrt(27.0)) == cbrt(27.0)) << std::endl;
std::cout << (is_cube(27.0)) << std::endl;
std::cout << (is_cube_inline(27.0)) << std::endl;




I would expect all outputs to be equal to 1, but it actually outputs this (g++ 8.3.1, no flags):



1
0
1


instead of



1
1
1


Edit: clang++ 7.0.0 outputs this:



0
0
0


and g++ -Ofast this:



1
1
1









share|improve this question









New contributor




zbrojny120 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












How can two versions of the same function, differing only in one being inline and the other one not, return different values? Here is some code I wrote today and I am not sure how it works.



#include <cmath>
#include <iostream>

bool is_cube(double r)

return floor(cbrt(r)) == cbrt(r);


bool inline is_cube_inline(double r)

return floor(cbrt(r)) == cbrt(r);


int main()

std::cout << (floor(cbrt(27.0)) == cbrt(27.0)) << std::endl;
std::cout << (is_cube(27.0)) << std::endl;
std::cout << (is_cube_inline(27.0)) << std::endl;




I would expect all outputs to be equal to 1, but it actually outputs this (g++ 8.3.1, no flags):



1
0
1


instead of



1
1
1


Edit: clang++ 7.0.0 outputs this:



0
0
0


and g++ -Ofast this:



1
1
1






c++






share|improve this question









New contributor




zbrojny120 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




zbrojny120 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Apr 10 at 2:49









chwarr

4,28811843




4,28811843






New contributor




zbrojny120 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Apr 9 at 10:11









zbrojny120zbrojny120

41348




41348




New contributor




zbrojny120 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





zbrojny120 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






zbrojny120 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 3





    Can you please provide what compiler, compiler options are you using and what machine ? Works ok for me on GCC 7.1 on Windows.

    – Diodacus
    Apr 9 at 10:13






  • 29





    Isn't == always a bit unpredictable with floating point values?

    – 500 - Internal Server Error
    Apr 9 at 10:15






  • 3





    related stackoverflow.com/questions/588004/…

    – user463035818
    Apr 9 at 10:16






  • 2





    Did you set the -Ofast option, which allows such optimizations?

    – cmdLP
    Apr 9 at 10:18






  • 4





    Compiler returns for cbrt(27.0) the value of 0x0000000000000840 while the standard library returns 0x0100000000000840. The doubles differ in 16th number after comma. My system: archlinux4.20 x64 gcc8.2.1 glibc2.28 Checked with this. Wonder if gcc or glibc is right.

    – Kamil Cuk
    Apr 9 at 10:59













  • 3





    Can you please provide what compiler, compiler options are you using and what machine ? Works ok for me on GCC 7.1 on Windows.

    – Diodacus
    Apr 9 at 10:13






  • 29





    Isn't == always a bit unpredictable with floating point values?

    – 500 - Internal Server Error
    Apr 9 at 10:15






  • 3





    related stackoverflow.com/questions/588004/…

    – user463035818
    Apr 9 at 10:16






  • 2





    Did you set the -Ofast option, which allows such optimizations?

    – cmdLP
    Apr 9 at 10:18






  • 4





    Compiler returns for cbrt(27.0) the value of 0x0000000000000840 while the standard library returns 0x0100000000000840. The doubles differ in 16th number after comma. My system: archlinux4.20 x64 gcc8.2.1 glibc2.28 Checked with this. Wonder if gcc or glibc is right.

    – Kamil Cuk
    Apr 9 at 10:59








3




3





Can you please provide what compiler, compiler options are you using and what machine ? Works ok for me on GCC 7.1 on Windows.

– Diodacus
Apr 9 at 10:13





Can you please provide what compiler, compiler options are you using and what machine ? Works ok for me on GCC 7.1 on Windows.

– Diodacus
Apr 9 at 10:13




29




29





Isn't == always a bit unpredictable with floating point values?

– 500 - Internal Server Error
Apr 9 at 10:15





Isn't == always a bit unpredictable with floating point values?

– 500 - Internal Server Error
Apr 9 at 10:15




3




3





related stackoverflow.com/questions/588004/…

– user463035818
Apr 9 at 10:16





related stackoverflow.com/questions/588004/…

– user463035818
Apr 9 at 10:16




2




2





Did you set the -Ofast option, which allows such optimizations?

– cmdLP
Apr 9 at 10:18





Did you set the -Ofast option, which allows such optimizations?

– cmdLP
Apr 9 at 10:18




4




4





Compiler returns for cbrt(27.0) the value of 0x0000000000000840 while the standard library returns 0x0100000000000840. The doubles differ in 16th number after comma. My system: archlinux4.20 x64 gcc8.2.1 glibc2.28 Checked with this. Wonder if gcc or glibc is right.

– Kamil Cuk
Apr 9 at 10:59






Compiler returns for cbrt(27.0) the value of 0x0000000000000840 while the standard library returns 0x0100000000000840. The doubles differ in 16th number after comma. My system: archlinux4.20 x64 gcc8.2.1 glibc2.28 Checked with this. Wonder if gcc or glibc is right.

– Kamil Cuk
Apr 9 at 10:59













2 Answers
2






active

oldest

votes


















63














Explanation



Some compilers (notably GCC) use higher precision when evaluating expressions at compile time. If an expression depends only on constant inputs and literals, it may be evaluated at compile time even if the expression is not assigned to a constexpr variable. Whether or not this occurs depends on:



  • The complexity of the expression

  • The threshold the compiler uses as a cutoff when attempting to perform compile time evaluation

  • Other heuristics used in special cases (such as when clang elides loops)

If an expression is explicitly provided, as in the first case, it has lower complexity and the compiler is likely to evaluate it at compile time.



Similarly, if a function is marked inline, the compiler is more likely to evaluate it at compile time because inline functions raise the threshold at which evaluation can occur.



Higher optimization levels also increase this threshold, as in the -Ofast example, where all expressions evaluate to true on gcc due to higher precision compile-time evaluation.



We can observe this behavior here on compiler explorer. When compiled with -O1, only the function marked inline is evaluated at compile-time, but at -O3 both functions are evaluated at compile-time.




  • -O1: https://godbolt.org/z/u4gh0g


  • -O3: https://godbolt.org/z/nVK4So

NB: In the compiler-explorer examples, I use printf instead iostream because it reduces the complexity of the main function, making the effect more visible.



Demonstrating that inline doesn’t affect runtime evaluation



We can ensure that none of the expressions are evaluated at compile time by obtaining value from standard input, and when we do this, all 3 expressions return false as demonstrated here: https://ideone.com/QZbv6X



#include <cmath>
#include <iostream>

bool is_cube(double r)

return floor(cbrt(r)) == cbrt(r);

 
bool inline is_cube_inline(double r)

return floor(cbrt(r)) == cbrt(r);


int main()

double value;
std::cin >> value;
std::cout << (floor(cbrt(value)) == cbrt(value)) << std::endl; // false
std::cout << (is_cube(value)) << std::endl; // false
std::cout << (is_cube_inline(value)) << std::endl; // false



Contrast with this example, where we use the same compiler settings but provide the value at compile-time, resulting in the higher-precision compile-time evaluation.






share|improve this answer
































    21














    As observed, using the == operator to compare floating point values has resulted in different outputs with different compilers and at different optimization levels.



    One good way to compare floating point values is the relative tolerance test outlined in the article: Floating-point tolerances revisited.



    We first calculate the Epsilon (the relative tolerance) value which in this case would be:



    double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();


    And then use it in both the inline and non-inline functions in this manner:



    return (std::fabs(std::floor(std::cbrt(r)) - std::cbrt(r)) < Epsilon);


    The functions now are:



    bool is_cube(double r)

    double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();
    return (std::fabs(std::floor(std::cbrt(r)) - std::cbrt(r)) < Epsilon);


    bool inline is_cube_inline(double r)

    double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();
    return (std::fabs(std::round(std::cbrt(r)) - std::cbrt(r)) < Epsilon);



    Now the output will be as expected ([1 1 1]) with different compilers and at different optimization levels.



    Live demo






    share|improve this answer

























    • What's the purpose of the max() call? By definition, floor(x) is less than or equal to x, so max(x, floor(x)) will always equal x.

      – Ken Thomases
      Apr 10 at 2:55











    • @KenThomases: In this particular case, where one argument to max is just the floor of the other, it is not required. But I considered a general case where arguments to max can be values or expressions which are independent of each other.

      – P.W
      Apr 10 at 4:10











    • Shouldn't operator==(double, double) do exactly that, check for the difference being smaller than a scaled epsilon? About 90% of floating point related questions on SO wouldn't exist then.

      – Peter A. Schneider
      Apr 10 at 10:13












    • I think it is better if the user gets to specify the Epsilon value depending on their particular requirement.

      – P.W
      Apr 10 at 10:20











    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    zbrojny120 is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55590324%2finline-version-of-a-function-returns-different-value-than-non-inline-version%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    63














    Explanation



    Some compilers (notably GCC) use higher precision when evaluating expressions at compile time. If an expression depends only on constant inputs and literals, it may be evaluated at compile time even if the expression is not assigned to a constexpr variable. Whether or not this occurs depends on:



    • The complexity of the expression

    • The threshold the compiler uses as a cutoff when attempting to perform compile time evaluation

    • Other heuristics used in special cases (such as when clang elides loops)

    If an expression is explicitly provided, as in the first case, it has lower complexity and the compiler is likely to evaluate it at compile time.



    Similarly, if a function is marked inline, the compiler is more likely to evaluate it at compile time because inline functions raise the threshold at which evaluation can occur.



    Higher optimization levels also increase this threshold, as in the -Ofast example, where all expressions evaluate to true on gcc due to higher precision compile-time evaluation.



    We can observe this behavior here on compiler explorer. When compiled with -O1, only the function marked inline is evaluated at compile-time, but at -O3 both functions are evaluated at compile-time.




    • -O1: https://godbolt.org/z/u4gh0g


    • -O3: https://godbolt.org/z/nVK4So

    NB: In the compiler-explorer examples, I use printf instead iostream because it reduces the complexity of the main function, making the effect more visible.



    Demonstrating that inline doesn’t affect runtime evaluation



    We can ensure that none of the expressions are evaluated at compile time by obtaining value from standard input, and when we do this, all 3 expressions return false as demonstrated here: https://ideone.com/QZbv6X



    #include <cmath>
    #include <iostream>

    bool is_cube(double r)

    return floor(cbrt(r)) == cbrt(r);

     
    bool inline is_cube_inline(double r)

    return floor(cbrt(r)) == cbrt(r);


    int main()

    double value;
    std::cin >> value;
    std::cout << (floor(cbrt(value)) == cbrt(value)) << std::endl; // false
    std::cout << (is_cube(value)) << std::endl; // false
    std::cout << (is_cube_inline(value)) << std::endl; // false



    Contrast with this example, where we use the same compiler settings but provide the value at compile-time, resulting in the higher-precision compile-time evaluation.






    share|improve this answer





























      63














      Explanation



      Some compilers (notably GCC) use higher precision when evaluating expressions at compile time. If an expression depends only on constant inputs and literals, it may be evaluated at compile time even if the expression is not assigned to a constexpr variable. Whether or not this occurs depends on:



      • The complexity of the expression

      • The threshold the compiler uses as a cutoff when attempting to perform compile time evaluation

      • Other heuristics used in special cases (such as when clang elides loops)

      If an expression is explicitly provided, as in the first case, it has lower complexity and the compiler is likely to evaluate it at compile time.



      Similarly, if a function is marked inline, the compiler is more likely to evaluate it at compile time because inline functions raise the threshold at which evaluation can occur.



      Higher optimization levels also increase this threshold, as in the -Ofast example, where all expressions evaluate to true on gcc due to higher precision compile-time evaluation.



      We can observe this behavior here on compiler explorer. When compiled with -O1, only the function marked inline is evaluated at compile-time, but at -O3 both functions are evaluated at compile-time.




      • -O1: https://godbolt.org/z/u4gh0g


      • -O3: https://godbolt.org/z/nVK4So

      NB: In the compiler-explorer examples, I use printf instead iostream because it reduces the complexity of the main function, making the effect more visible.



      Demonstrating that inline doesn’t affect runtime evaluation



      We can ensure that none of the expressions are evaluated at compile time by obtaining value from standard input, and when we do this, all 3 expressions return false as demonstrated here: https://ideone.com/QZbv6X



      #include <cmath>
      #include <iostream>

      bool is_cube(double r)

      return floor(cbrt(r)) == cbrt(r);

       
      bool inline is_cube_inline(double r)

      return floor(cbrt(r)) == cbrt(r);


      int main()

      double value;
      std::cin >> value;
      std::cout << (floor(cbrt(value)) == cbrt(value)) << std::endl; // false
      std::cout << (is_cube(value)) << std::endl; // false
      std::cout << (is_cube_inline(value)) << std::endl; // false



      Contrast with this example, where we use the same compiler settings but provide the value at compile-time, resulting in the higher-precision compile-time evaluation.






      share|improve this answer



























        63












        63








        63







        Explanation



        Some compilers (notably GCC) use higher precision when evaluating expressions at compile time. If an expression depends only on constant inputs and literals, it may be evaluated at compile time even if the expression is not assigned to a constexpr variable. Whether or not this occurs depends on:



        • The complexity of the expression

        • The threshold the compiler uses as a cutoff when attempting to perform compile time evaluation

        • Other heuristics used in special cases (such as when clang elides loops)

        If an expression is explicitly provided, as in the first case, it has lower complexity and the compiler is likely to evaluate it at compile time.



        Similarly, if a function is marked inline, the compiler is more likely to evaluate it at compile time because inline functions raise the threshold at which evaluation can occur.



        Higher optimization levels also increase this threshold, as in the -Ofast example, where all expressions evaluate to true on gcc due to higher precision compile-time evaluation.



        We can observe this behavior here on compiler explorer. When compiled with -O1, only the function marked inline is evaluated at compile-time, but at -O3 both functions are evaluated at compile-time.




        • -O1: https://godbolt.org/z/u4gh0g


        • -O3: https://godbolt.org/z/nVK4So

        NB: In the compiler-explorer examples, I use printf instead iostream because it reduces the complexity of the main function, making the effect more visible.



        Demonstrating that inline doesn’t affect runtime evaluation



        We can ensure that none of the expressions are evaluated at compile time by obtaining value from standard input, and when we do this, all 3 expressions return false as demonstrated here: https://ideone.com/QZbv6X



        #include <cmath>
        #include <iostream>

        bool is_cube(double r)

        return floor(cbrt(r)) == cbrt(r);

         
        bool inline is_cube_inline(double r)

        return floor(cbrt(r)) == cbrt(r);


        int main()

        double value;
        std::cin >> value;
        std::cout << (floor(cbrt(value)) == cbrt(value)) << std::endl; // false
        std::cout << (is_cube(value)) << std::endl; // false
        std::cout << (is_cube_inline(value)) << std::endl; // false



        Contrast with this example, where we use the same compiler settings but provide the value at compile-time, resulting in the higher-precision compile-time evaluation.






        share|improve this answer















        Explanation



        Some compilers (notably GCC) use higher precision when evaluating expressions at compile time. If an expression depends only on constant inputs and literals, it may be evaluated at compile time even if the expression is not assigned to a constexpr variable. Whether or not this occurs depends on:



        • The complexity of the expression

        • The threshold the compiler uses as a cutoff when attempting to perform compile time evaluation

        • Other heuristics used in special cases (such as when clang elides loops)

        If an expression is explicitly provided, as in the first case, it has lower complexity and the compiler is likely to evaluate it at compile time.



        Similarly, if a function is marked inline, the compiler is more likely to evaluate it at compile time because inline functions raise the threshold at which evaluation can occur.



        Higher optimization levels also increase this threshold, as in the -Ofast example, where all expressions evaluate to true on gcc due to higher precision compile-time evaluation.



        We can observe this behavior here on compiler explorer. When compiled with -O1, only the function marked inline is evaluated at compile-time, but at -O3 both functions are evaluated at compile-time.




        • -O1: https://godbolt.org/z/u4gh0g


        • -O3: https://godbolt.org/z/nVK4So

        NB: In the compiler-explorer examples, I use printf instead iostream because it reduces the complexity of the main function, making the effect more visible.



        Demonstrating that inline doesn’t affect runtime evaluation



        We can ensure that none of the expressions are evaluated at compile time by obtaining value from standard input, and when we do this, all 3 expressions return false as demonstrated here: https://ideone.com/QZbv6X



        #include <cmath>
        #include <iostream>

        bool is_cube(double r)

        return floor(cbrt(r)) == cbrt(r);

         
        bool inline is_cube_inline(double r)

        return floor(cbrt(r)) == cbrt(r);


        int main()

        double value;
        std::cin >> value;
        std::cout << (floor(cbrt(value)) == cbrt(value)) << std::endl; // false
        std::cout << (is_cube(value)) << std::endl; // false
        std::cout << (is_cube_inline(value)) << std::endl; // false



        Contrast with this example, where we use the same compiler settings but provide the value at compile-time, resulting in the higher-precision compile-time evaluation.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 9 at 11:28

























        answered Apr 9 at 10:25









        Jorge PerezJorge Perez

        2,424920




        2,424920























            21














            As observed, using the == operator to compare floating point values has resulted in different outputs with different compilers and at different optimization levels.



            One good way to compare floating point values is the relative tolerance test outlined in the article: Floating-point tolerances revisited.



            We first calculate the Epsilon (the relative tolerance) value which in this case would be:



            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();


            And then use it in both the inline and non-inline functions in this manner:



            return (std::fabs(std::floor(std::cbrt(r)) - std::cbrt(r)) < Epsilon);


            The functions now are:



            bool is_cube(double r)

            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();
            return (std::fabs(std::floor(std::cbrt(r)) - std::cbrt(r)) < Epsilon);


            bool inline is_cube_inline(double r)

            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();
            return (std::fabs(std::round(std::cbrt(r)) - std::cbrt(r)) < Epsilon);



            Now the output will be as expected ([1 1 1]) with different compilers and at different optimization levels.



            Live demo






            share|improve this answer

























            • What's the purpose of the max() call? By definition, floor(x) is less than or equal to x, so max(x, floor(x)) will always equal x.

              – Ken Thomases
              Apr 10 at 2:55











            • @KenThomases: In this particular case, where one argument to max is just the floor of the other, it is not required. But I considered a general case where arguments to max can be values or expressions which are independent of each other.

              – P.W
              Apr 10 at 4:10











            • Shouldn't operator==(double, double) do exactly that, check for the difference being smaller than a scaled epsilon? About 90% of floating point related questions on SO wouldn't exist then.

              – Peter A. Schneider
              Apr 10 at 10:13












            • I think it is better if the user gets to specify the Epsilon value depending on their particular requirement.

              – P.W
              Apr 10 at 10:20















            21














            As observed, using the == operator to compare floating point values has resulted in different outputs with different compilers and at different optimization levels.



            One good way to compare floating point values is the relative tolerance test outlined in the article: Floating-point tolerances revisited.



            We first calculate the Epsilon (the relative tolerance) value which in this case would be:



            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();


            And then use it in both the inline and non-inline functions in this manner:



            return (std::fabs(std::floor(std::cbrt(r)) - std::cbrt(r)) < Epsilon);


            The functions now are:



            bool is_cube(double r)

            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();
            return (std::fabs(std::floor(std::cbrt(r)) - std::cbrt(r)) < Epsilon);


            bool inline is_cube_inline(double r)

            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();
            return (std::fabs(std::round(std::cbrt(r)) - std::cbrt(r)) < Epsilon);



            Now the output will be as expected ([1 1 1]) with different compilers and at different optimization levels.



            Live demo






            share|improve this answer

























            • What's the purpose of the max() call? By definition, floor(x) is less than or equal to x, so max(x, floor(x)) will always equal x.

              – Ken Thomases
              Apr 10 at 2:55











            • @KenThomases: In this particular case, where one argument to max is just the floor of the other, it is not required. But I considered a general case where arguments to max can be values or expressions which are independent of each other.

              – P.W
              Apr 10 at 4:10











            • Shouldn't operator==(double, double) do exactly that, check for the difference being smaller than a scaled epsilon? About 90% of floating point related questions on SO wouldn't exist then.

              – Peter A. Schneider
              Apr 10 at 10:13












            • I think it is better if the user gets to specify the Epsilon value depending on their particular requirement.

              – P.W
              Apr 10 at 10:20













            21












            21








            21







            As observed, using the == operator to compare floating point values has resulted in different outputs with different compilers and at different optimization levels.



            One good way to compare floating point values is the relative tolerance test outlined in the article: Floating-point tolerances revisited.



            We first calculate the Epsilon (the relative tolerance) value which in this case would be:



            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();


            And then use it in both the inline and non-inline functions in this manner:



            return (std::fabs(std::floor(std::cbrt(r)) - std::cbrt(r)) < Epsilon);


            The functions now are:



            bool is_cube(double r)

            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();
            return (std::fabs(std::floor(std::cbrt(r)) - std::cbrt(r)) < Epsilon);


            bool inline is_cube_inline(double r)

            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();
            return (std::fabs(std::round(std::cbrt(r)) - std::cbrt(r)) < Epsilon);



            Now the output will be as expected ([1 1 1]) with different compilers and at different optimization levels.



            Live demo






            share|improve this answer















            As observed, using the == operator to compare floating point values has resulted in different outputs with different compilers and at different optimization levels.



            One good way to compare floating point values is the relative tolerance test outlined in the article: Floating-point tolerances revisited.



            We first calculate the Epsilon (the relative tolerance) value which in this case would be:



            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();


            And then use it in both the inline and non-inline functions in this manner:



            return (std::fabs(std::floor(std::cbrt(r)) - std::cbrt(r)) < Epsilon);


            The functions now are:



            bool is_cube(double r)

            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();
            return (std::fabs(std::floor(std::cbrt(r)) - std::cbrt(r)) < Epsilon);


            bool inline is_cube_inline(double r)

            double Epsilon = std::max(std::cbrt(r), std::floor(std::cbrt(r))) * std::numeric_limits<double>::epsilon();
            return (std::fabs(std::round(std::cbrt(r)) - std::cbrt(r)) < Epsilon);



            Now the output will be as expected ([1 1 1]) with different compilers and at different optimization levels.



            Live demo







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 9 at 13:01

























            answered Apr 9 at 11:06









            P.WP.W

            18.7k41859




            18.7k41859












            • What's the purpose of the max() call? By definition, floor(x) is less than or equal to x, so max(x, floor(x)) will always equal x.

              – Ken Thomases
              Apr 10 at 2:55











            • @KenThomases: In this particular case, where one argument to max is just the floor of the other, it is not required. But I considered a general case where arguments to max can be values or expressions which are independent of each other.

              – P.W
              Apr 10 at 4:10











            • Shouldn't operator==(double, double) do exactly that, check for the difference being smaller than a scaled epsilon? About 90% of floating point related questions on SO wouldn't exist then.

              – Peter A. Schneider
              Apr 10 at 10:13












            • I think it is better if the user gets to specify the Epsilon value depending on their particular requirement.

              – P.W
              Apr 10 at 10:20

















            • What's the purpose of the max() call? By definition, floor(x) is less than or equal to x, so max(x, floor(x)) will always equal x.

              – Ken Thomases
              Apr 10 at 2:55











            • @KenThomases: In this particular case, where one argument to max is just the floor of the other, it is not required. But I considered a general case where arguments to max can be values or expressions which are independent of each other.

              – P.W
              Apr 10 at 4:10











            • Shouldn't operator==(double, double) do exactly that, check for the difference being smaller than a scaled epsilon? About 90% of floating point related questions on SO wouldn't exist then.

              – Peter A. Schneider
              Apr 10 at 10:13












            • I think it is better if the user gets to specify the Epsilon value depending on their particular requirement.

              – P.W
              Apr 10 at 10:20
















            What's the purpose of the max() call? By definition, floor(x) is less than or equal to x, so max(x, floor(x)) will always equal x.

            – Ken Thomases
            Apr 10 at 2:55





            What's the purpose of the max() call? By definition, floor(x) is less than or equal to x, so max(x, floor(x)) will always equal x.

            – Ken Thomases
            Apr 10 at 2:55













            @KenThomases: In this particular case, where one argument to max is just the floor of the other, it is not required. But I considered a general case where arguments to max can be values or expressions which are independent of each other.

            – P.W
            Apr 10 at 4:10





            @KenThomases: In this particular case, where one argument to max is just the floor of the other, it is not required. But I considered a general case where arguments to max can be values or expressions which are independent of each other.

            – P.W
            Apr 10 at 4:10













            Shouldn't operator==(double, double) do exactly that, check for the difference being smaller than a scaled epsilon? About 90% of floating point related questions on SO wouldn't exist then.

            – Peter A. Schneider
            Apr 10 at 10:13






            Shouldn't operator==(double, double) do exactly that, check for the difference being smaller than a scaled epsilon? About 90% of floating point related questions on SO wouldn't exist then.

            – Peter A. Schneider
            Apr 10 at 10:13














            I think it is better if the user gets to specify the Epsilon value depending on their particular requirement.

            – P.W
            Apr 10 at 10:20





            I think it is better if the user gets to specify the Epsilon value depending on their particular requirement.

            – P.W
            Apr 10 at 10:20










            zbrojny120 is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            zbrojny120 is a new contributor. Be nice, and check out our Code of Conduct.












            zbrojny120 is a new contributor. Be nice, and check out our Code of Conduct.











            zbrojny120 is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55590324%2finline-version-of-a-function-returns-different-value-than-non-inline-version%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            getting Checkpoint VPN SSL Network Extender working in the command lineHow to connect to CheckPoint VPN on Ubuntu 18.04LTS?Will the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayVPN SSL Network Extender in FirefoxLinux Checkpoint SNX tool configuration issuesCheck Point - Connect under Linux - snx + OTPSNX VPN Ububuntu 18.XXUsing Checkpoint VPN SSL Network Extender CLI with certificateVPN with network manager (nm-applet) is not workingWill the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayImport VPN config files to NetworkManager from command lineTrouble connecting to VPN using network-manager, while command line worksStart a VPN connection with PPTP protocol on command linestarting a docker service daemon breaks the vpn networkCan't connect to vpn with Network-managerVPN SSL Network Extender in FirefoxUsing Checkpoint VPN SSL Network Extender CLI with certificate

            Cannot Extend partition with GParted The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election ResultsCan't increase partition size with GParted?GParted doesn't recognize the unallocated space after my current partitionWhat is the best way to add unallocated space located before to Ubuntu 12.04 partition with GParted live?I can't figure out how to extend my Arch home partition into free spaceGparted Linux Mint 18.1 issueTrying to extend but swap partition is showing as Unknown in Gparted, shows proper from fdiskRearrange partitions in gparted to extend a partitionUnable to extend partition even though unallocated space is next to it using GPartedAllocate free space to root partitiongparted: how to merge unallocated space with a partition

            Marilyn Monroe Ny fiainany manokana | Jereo koa | Meny fitetezanafanitarana azy.