Assuming the following function's logic always works:
1 2 3 4 5
void f(double* xa, double* xb, double a, double b) {
assert( xa && xb);
*xa = *xb + a - b;
*xb = *xa + 5 * b;
}
If you saw it in a production code, how should you change it for the better?
My answers are (a) playing with pointers are generally more dangerous than using references; In the above function, use references instread. (b) the assert statement on line 2 should throw an exception and add an exception handler for it. Is the following one really better than the original one?
1 2 3 4
void f(double& xa, double& xb, constdouble a, constdouble b) {
xa = xb + a - b;
xb = xa + 5 * b;
}
Just for extremely minor efficiency, you could also make a and b references. That way copies of them do not have to be made. I usually make all my parameters references, even pointers, unless I want to use the parameter as a local variable.
With no regard toward efficency (I just deleted a two paragraph rant about how I feel regarding that term) I think this code is ugly because it should be using objects. That would certainly make it look cleaner.
(b) the assert statement on line 2 should throw an exception and add an exception handler for it. Is the following one really better than the original one?
No. Exceptions are for "release mode". The assert is for debugging purposes, and will only be compiled into the application when compiling in "debug mode".