CSADPRG_mod4_overloaded_operators
original file
this is unedited
overloaded operators
- Arithmetic operators are often used for more than one purpose. For example in Java,
+
can be used for integer and floating point addition BUT can also be used for string concatenation - The multiple use of an operator is called OPERATOR OVERLOADING. It is generally acceptable unless it inhibits readability or reliability.
dangers
In C/C++ & can be a binary operator that specifies a bitwise logical AND
unsigned char a = 5, b = 4;
printf("a&b = %d\n", a & b);
// output: a&b = 4
// x = &y; can be a unary operator for getting the address of a variable
- Some languages like C++ and C# allow the programmer to overload operator symbols. For example the user can define the * operator between a scalar integer and an integer array to be multiplied by a scalar. This can aid readability when sensibly used. For example if + and * are overloaded for a matrix data type
A * B + C * D
can be used instead ofMatrixAdd(MatrixMult(A, B), MatrixMult(C, D))
- However, it can also be detrimental to readability. What if a user re-defines + to mean multiplication?