Using the C++ Math Library | ![]() ![]() |
Casting an Argument to Avoid a Name Conflict
The most common naming conflicts between the two libraries occur with the trigonometric functions (sin()
, cos()
, tan()
, etc.), the logarithmic and exponential functions (log()
, log10()
and exp()
), and several miscellaneous functions like sqrt()
and abs()
. These duplicate functions cause a problem when invoked with either a C++ int
or double
scalar argument. They do not cause a problem when they're invoked with an mwArray
argument.
For example, when the C++ compiler sees a call such as sqrt(-1)
, it generates a call to the sqrt()
defined in the standard C math library rather than the sqrt()
defined by the MATLAB C++ Math Library. The C runtime library conforms to the IEEE standard: the square root of a negative number is NaN
. However, the range of the MATLAB C++ Math Library's sqrt()
routine extends into the complex plane, so that it returns the complex number i
when called with -1
.
Because C++ does not allow a function name to be overloaded on the basis of return type alone, it is not possible to add functions to the MATLAB C++ Math Library that take scalars and return mwArray
's and thus distinguish between a function in the standard C math library and one in the MATLAB C++ Math Library. Renaming all the MATLAB functions like sqrt()
and abs()
would only cause confusion. Therefore, to avoid this problem, we recommend that you never invoke these functions with a scalar argument.
For example, if you need to determine the square root of a negative quantity, first create an array and assign the negative number to it. Then call sqrt()
on the array:
mwArray a = -5; sqrt(a);
sqrt((mwArray)-5);
or an explicit constructor call:
sqrt(mwArray(-5));
The last two techniques are the most succinct.
![]() | Name Conflicts with Standard C Library Functions | Renaming Functions to Avoid a Name Conflict | ![]() |