Pass by reference and global variable


#1

is pass by reference and global variable the same thing?
Because we can use the pointer with the address to obtain value out of the function.
Global variable does the same thing, just that we need to declare it outside the function.


#2

No, they are not the same thing.

A global variable is used to store a value; pass-by reference is used to pass the address of an object, not its value, in a function or method invocation.

However, as you said, the same effect can be achieved with global variables instead of defining a function which takes pass-by reference arguments.

But it is better not to do this, as doing so leads to functions that are harder to read and harder to document.

For example, transferring information by using a global variable:

long _my_error_code;
...
bool DoSomething ()
{
     ...
     // failed - set global-error-code variable
     _my_errorCode = ERROR_CODE_1024;
     return false;
     ...
     // no errors
     return true;
}

Transferring information by using a local variable the value of which is passed by reference:

bool DoSomething (const long *errorCode)
{
     ...
     // failed
     *errorCode = ERROR_CODE_1024;
     return false;
     ...
     // no errors
     return true;
}

Now, even in this simple example, which method leads to code that is easier to read?