I’m just learning c++, and coming from c, some function calls I’m seeing in the book confuse me:
char a;
cin.get(a);
In C, this couldn’t possibly work, if you did that, there would be no way to get the output, because you are passing by value, and not by reference, why does this work in c++? Is referencing and dereferncing made implicit (the compiler knows that cin.get needs a pointer, so it is referenced)?
C++
This would work in C++ because the function signature for
get()is probably this:The
&symbol afterchardenotes to the compiler than when you pass in acharvalue, it should pass in a reference to thecharrather than making a copy of it.What this essentially means is that any changes made within
get()will be reflected in the value ofaoutside the method.If the function signature for
get()was this:then
awould be passed by value, which means a copy ofais made before being passed into the method as a parameter. Any changes toawould 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:
Running this program will output: