C++
This would work in C++ because the function signature for get()
is probably this:
void get(char& a); // pass-by-reference
The &
symbol after char
denotes to the compiler than when you pass in a char
value, it should pass in a reference to the char
rather than making a copy of it.
What this essentially means is that any changes made within get()
will be reflected in the value of a
outside the method.
If the function signature for get()
was this:
void get(char a); // pass-by-value
then a
would be passed by value, which means a copy of a
is made before being passed into the method as a parameter. Any changes to a
would then only be local the method, and lost when the method returns.
C
The reason why this wouldn't work in C is because C only has pass-by-value. The only way to emulate pass-by-reference behaviour in C is to pass its pointer by value, and then de-reference the pointer value (thus accessing the same memory location) when modifying the value within the method:
void get(char* a)
{
*a = 'g';
}
int main(int argc, char* argv[])
{
char a = 'f';
get(&a);
printf("%c\n", a);
return 0;
}
Running this program will output:
g