Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqrt(int_value + 0.0) -- Does it have a purpose?

Tags:

c++

casting

while doing some homework in my very strange C++ book, which I've been told before to throw away, had a very peculiar code segment. I know homework stuff always throws in extra "mystery" to try to confuse you like indenting 2 lines after a single-statement for-loop. But this one I'm confused on because it seems to serve some real-purpose.

basically it is like this:

int counter=10;
...
if(pow(floor(sqrt(counter+0.0)),2) == counter)
...

I'm interested in this part especially:

sqrt(counter+0.0)

Is there some purpose to the +0.0? Is this the poormans way of doing a static cast to a double? Does this avoid some compiler warning on some compiler I do not use? The entire program printed the exact same thing and compiled without warnings on g++ whenever I left out the +0.0 part. Maybe I'm not using a weird enough compiler?

Edit:

Also, does gcc just break standard and not make an error for Ambiguous reference since sqrt can take 3 different types of parameters?

[earlz@EarlzBeta-~/projects/homework1] $ cat calc.cpp
#include <cmath>

int main(){
  int counter=0;
  sqrt(counter);
}
[earlz@EarlzBeta-~/projects/homework1] $ g++ calc.cpp
/usr/lib/libstdc++.so.47.0: warning: strcpy() is almost always misused, please use strlcpy()
/usr/lib/libstdc++.so.47.0: warning: strcat() is almost always misused, please use strlcat()
[earlz@EarlzBeta-~/projects/homework1] $

Also, here is the relevant part of my system libraries cmath I'm not too keen on templates, so I'm not sure what it's doing

  using ::sqrt;

  inline float
  sqrt(float __x)
  { return __builtin_sqrtf(__x); }

  inline long double
  sqrt(long double __x)
  { return __builtin_sqrtl(__x); }

  template<typename _Tp>
    inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
                       double>::__type
    sqrt(_Tp __x)
    { return __builtin_sqrt(__x);
like image 701
Earlz Avatar asked Apr 12 '10 04:04

Earlz


1 Answers

Is this the poormans way of doing a static cast to a double?

Yes.

You can't call sqrt with an int as its parameter, because sqrt takes a float, double, or long double. You have to cast the int to one of those types, otherwise the call is ambiguous.

like image 116
James McNellis Avatar answered Sep 26 '22 05:09

James McNellis