2

In the following source, why does the DEG_TO_RAD_B constant evaluate to 0?

/// @file Main.cpp

// Includes

#include <cmath>
#include <iostream>


// Constant definitions

template <typename T>
const T PI
    = std::acos(-T(1));

const float DEG_TO_RAD_A                // good - evaluates to 0.0174533
    = std::acos(-float(1)) / 180.0f;

const float DEG_TO_RAD_B                //  bad - evaluates to 0
    = PI<float> / 180.0f;


/// Process entry point

int main()
{
    float deg_to_rad = PI<float> / 180.0f;

    std::cout << "PI:           " << PI<float>    << std::endl; // good - 3.14159
    std::cout << "deg_to_rad:   " << deg_to_rad   << std::endl; // good - 0.0174533
    std::cout << "DEG_TO_RAD_A: " << DEG_TO_RAD_A << std::endl; // good - 0.0174533
    std::cout << "DEG_TO_RAD_B: " << DEG_TO_RAD_B << std::endl; //  bad - 0

    return 0;
}

Output using Visual Studio Community 2019 version 16.4.5:

PI:           3.14159
deg_to_rad:   0.0174533
DEG_TO_RAD_A: 0.0174533
DEG_TO_RAD_B: 0

_MSC_VER : 1924
_MSC_FULL_VER : 192428316
_MSC_BUILD : 0
_MSVC_LANG : C++17

Not receiving any compiler warnings. Same output regardless of x86/x64/debug/release configuration setting.

  • 5
    [Can't reproduce](https://godbolt.org/z/SL8-N4). – Evg Apr 28 '20 at 11:49
  • 2
    which compiler? Are you sure that this is the code that produces unexpected output? Including the output in the question also helps to avoid misunderstanding (you have it in comments, but comments are liars) – 463035818_is_not_an_ai Apr 28 '20 at 11:50
  • 1
    I can reproduce with `clang-cl` in `MSVC` (VS 2019, latest update). The following warning is generated (multiple times): **declaration requires a global constructor**. Maybe [this post](https://stackoverflow.com/q/15708411/10871073) is helpful? – Adrian Mole Apr 28 '20 at 11:54
  • 1
    @idclev463035818 edited my post to add console output and compiler version numbers. – S. McPharlin Apr 28 '20 at 12:14
  • @AdrianMole no warnings generated, sadly. – S. McPharlin Apr 28 '20 at 12:17
  • I also have no warnings with MSVC, even when I run the code analysis. However, I have noticed this 'global constructor' warning from clang in other situations (can't pull one out, off-hand, though). I'm not entirely sure what it means, but I'm sure it's trying to give us a clue. – Adrian Mole Apr 28 '20 at 12:27

0 Answers0