abs vs std :: abs, was sagt die Referenz?
Vorsicht, ich spreche::abs()
nichtstd::abs()
Lautcplusplus.com Webseite, abs
soll sich für die anders verhaltenstdlib.
h C-Version, wenn Sie einschließen<cmath>
Hier ist ein Auszug aus dieser Seite (die sich mit::abs
nichtstd::abs
):
double abs (double x);
float abs (float x);
long double abs (long double x);
Compute absolute value
/*
Returns the absolute value of x: |x|.
These convenience abs overloads are exclusive of C++. In C, abs is only declared
in <cstdlib> (and operates on int values).
The additional overloads are provided in this header (<cmath>) for the integral types:
These overloads effectively cast x to a double before calculations
(defined for T being any integral type).
*/
Ja wirklich???
Das hat mich beim Portieren eines Programms auf eine neue Plattform gebissen, da sich die Implementierung der verschiedenen Compiler und Standardbibliotheken hier unterscheidet.
Hier ist mein Beispielprogramm:
#include <iostream>
//#include <stdlib.h>//Necessary inclusion compil under linux
//You can include either cmath or math.h, the result is the same
//#include <cmath>
#include <math.h>
int main(int argc, const char * argv[])
{
double x = -1.5;
double ax = std::abs(x);
std::cout << "x=" << x << " ax=" << ax << std::endl;
return 0;
}
Und hier ist das Ergebnis unter MSVC 2010:
Unter MSVC 2010 wird keine Kompilierungswarnung ausgegeben, und das Programm wird kompiliert, auch wenn Sie weder math.h noch einschließenstdlib.h
: wie es scheintmath.h
undstdlib.h
sind immer dabei, was auch immer Sie tunDie Programmausgabe ist:x=-1.5 ax=1.5
(scheinbar richtig laut Hinweis)Hier ist das Ergebnis unter OSX:
Es wird keine Kompilierungswarnung ausgegeben, auch nicht mit-Wall
flag (der double to int cast wird nicht signalisiert)! Das Ergebnis ist das gleiche, wenn Sie ersetzeng++
durchllvm-g++
. Die Aufnahme vonmath.h
odercmath
wird für die Zusammenstellung nicht benötigt.Die Programmausgabe ist:x=-1.5 ax=1
Und zum Schluss das Ergebnis unter Linux:
Das Programm wird nicht kompiliert, wennstdlib.h
ist nicht enthalten (endlich ein Compiler, der nicht enthält)stdlib
automatisch). Für den double -> int-Cast wird keine Kompilierungswarnung ausgegeben.Die Programmausgabe ist:x=-1.5 ax=1
Kein klarer Gewinner hier. Ich weiß, dass eine offensichtliche Antwort "bevorzugen" iststd::abs
zu::abs
", Aber ich frage mich:
abs
sollte automatisch die doppelte Version außerhalb des bereitstellenstd
Namespace?Sind alle Compiler und ihre Standardbibliotheken hier falsch, mit Ausnahme von MSVC (obwohl es enthältmath.h
schweigend)?