So this is a purely academic question, mostly as its been a while since I’ve done anything too complex in C++. But is there any way to know if a method is taking a paramter as a reference or a value? This isn’t important for pointers, as if you try to pass a non-pointer to a method that takes a pointer, you get a compile error. But something like
int someFunction(int &x){
x = 0
return x;
}
int main(){
int v = 4;
int l = someFunction(v);
I realize that this could be avoided by declaring v as const. But I was just wondering if there was a way to know at runtime if someFunction is taking a reference or a value?
Tagged as C and C++, is there a difference in how either one handles this?
My mistake about C. It's been a long time since I've worked in just C and I've forgotten exactly where the boundary is, lol
Yes. In any language it is possible to create a function that returns different results based on whether the function uses pass-by-value or pass-by-reference. This shouldn’t be used in day-to-day programming, but it is useful for testing the compiler, testing an API, etc. Basically, call your function with a variable that is initialized to some value, and in the function, assign a different value to the parameter. In the caller, check the value of the parameter after you’ve invoked the function to see if the mutation has had a visible effect. Note that I am assuming that you’ve written both the caller and the callee.
If you want to check some arbitrary function that you don’t have control over, you can use function overloading to tell you what type of parameter passing scheme is in use:
As has been noted, this is applicable to C++ only. (C has pointers, but no references).