I have a legacy interface that has a function with a signature that looks like the following:
int provide_values(int &x, int &y)
x
and y
are considered output parameters in this function. Note: I'm aware of the drawbacks of using output parameters and that there are better design choices for such an interface. I'm not trying to debate the merits of this interface.
Within the implementation of this function, it first checks to see if the addresses of the two output parameters are the same, and returns an error code if they are.
if (&x == &y) {
return -1; // Error: both output parameters are the same variable
}
Is there a way at compile time to prevent callers of this function from providing the same variable for the two output parameters without having such a check within the body of the function? I'm thinking of something similar to the restrict
keyword in C, but that only is a signal to the compiler for optimization, and only provides a warning
when compiling code that calls such a function with the same pointer.
No, there's not. Keep in mind that the calling code could derive x
and y
from references returned from some arbitrary black-box functions. But even otherwise, it is provably impossible (by the Incompleteness Theorem) for the compiler to robustly determine whether they point to the same object, since what objects they are bound to is determined by the execution of the program.