Skip to content

Abs, std::abs, cmath, math.h #286

Description

@ToppDev

Channel

C++Weekly

Topics

Differences in the behavior of abs and std::abs depending on includes. (Compiler Explorer)

#include<cmath>autostd_abs(auto val) { returnstd::abs(val); }
autoabs_cmath(auto val) { returnabs(val); }
#include<math.h>autoabs_math_h(auto val) { returnabs(val); }
#include<iostream>intmain ()
{
std::cout << "std::abs (3.1416) = " << std_abs(3.1416) << '\n';
std::cout << "abs_cmath (3.1416) = " << abs_cmath(3.1416) << '\n';
std::cout << "abs_math_h (3.1416) = " << abs_math_h(3.1416) << '\n';
return0;
}

Result

std::abs (3.1416) = 3.1416
abs_cmath (3.1416) = 3
abs_math_h (3.1416) = 3.1416

Compiler differences:

  • gcc does not warn
  • clang throws a warning
  • apple clang does not cut the value

Length

5-10 minutes

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions