I'm try to compile this code:
#include <cmath>
double gravity (double level) {
return 0.02 * std::round(level);
}
But GCC is telling me:
error: 'round' is not a member of 'std'
I know I've used the round
function many times in ISO C++98 before. Unusually, round
and ::round
both work.
What gives?
Update: I was compiling with g++ -std=c++98 -Wall -pedantic
.
Switching to std=c++0x
works.
But why do the unqualified/anonymous round
and ::round
both work if std::round
doesn't?
The std::round function returns a floating point value, "rounding halfway cases away from zero".
The round() function in C++ is used to round off the double, float or long double value passed to it as a parameter to the nearest integral value. The header file used to use the round() function in a c++ program is <cmath> or <tgmath>.
C++ round() The round() function in C++ returns the integral value that is nearest to the argument, with halfway cases rounded away from zero. It is defined in the cmath header file.
The std::round
functions are C++11, so you would need to compile with C++11 or a more recent standard enabled.
I've done a bit of research, here's what I've found:
round
is defined in ISO C++11, as it contains the ISO C99 standard library.
round
is not part of the ISO C++98, which uses the ISO C90 standard library.
That's why it's not in namespace std
for C++98.
But g++
is (incorrectly) including the C99 headers, even when compiled with -std=c++98 -pedantic
, which should disable all non-standard stuff:
GNU_SOURCE is defined by G++ and ... it implies _USE_ISOC99
(from http://gcc.gnu.org/ml/gcc/2002-09/msg00580.html)
This is why ::round
works.
This apparently is a bug in GCC: Why does GCC allow use of round() in C++ even with the ansi and pedantic flags?
Other C++ compilers may not provide a round
function (since it's not required by the standard), so I should define my own.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With