Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default argument of type float = gibberish

I have some trouble using a default argument of type float:

#include <wchar.h>
#include <iostream>

template<typename T>
void fun(T t = 1e-05);

template<typename T> inline
void fun(T t)
{
    std::cout << t << std::endl;
}

int wmain(int argc, wchar_t* argv[])
{
    fun<float>();

    _getwch();
    return 0;
}

It prints -1.36867e-033 instead of the equivalence of 1e-05. What is going on here?

I'm using VC++10.

EDIT1:

Thank you all for your replies. But casting the default argument doesn't work in the following case:

template<typename T>
void fun(T t = static_cast<T>(1e-05));

template<typename T> inline
void fun(T t)
{
    std::wcout << t << std::endl;
}

int wmain(int argc, wchar_t* argv[])
{
    fun<double>();
    fun<float>();

    _getwch();
    return 0;
}

So this is definitely a bug and worth reporting?

EDIT2:

Reported this issue to Microsoft

like image 543
Nubcase Avatar asked Jun 30 '11 10:06

Nubcase


1 Answers

Looks to be an issue with a default template argument and conversion between double and float. The issue doesn't occur if you aren't using templates.

Stick an "f" at the end of that default template argument such that it treats the value as a "float" instead of a double. That seems to fix it.

template<typename T>
void fun(T t = 1e-05f);

But after applying the above fix, if you declare this

fun<double>()

you get an equivalent bug. So a better fix that works for both floats and doubles is to use a cast as follows:

template<typename T>
void fun(T t = (T)(1e-05));

As to whether this is a compiler bug or "undefined behavior", I'll let the compiler gurus chime in.

like image 131
selbie Avatar answered Nov 18 '22 10:11

selbie