I need to create a variable in a main function, pass it's reference to another function, then use that reference in the second function to alter the variable in the first. I forgot the syntax, can someone help me out? Thanks.
void main()
{
int foo = 5;
increment_foo(foo);
}
void increment_foo(int &bar)
{
bar++;
}
void main()
{
int foo = 5;
increment_foo(&foo);
}
void increment_foo(int *bar)
{
*bar++;
}
So foo is a declared variable with a set amount of memory, then you pass a reference to that variable
fun(arg); // Reference argument, no indication that arg will be changed.
fun(&arg); // Pointer argument, clear indication that arg is likely to be changed.
Hmm, I'm not sure I agree with this. One can distingusih between the two situations with const references, and the compiler will go some way to tray and enforce that, too. Given declarationsWhen declaring a function that changes its argument, it's more polite to use a pointer, thereby clearly indicating that the argument variable is going to be modified by the function. Compare the function calls:
[...]
int function_one(Foo &f);
int function_two(const Foo &f);
To keep a program readable, it is often best to avoid functions that modify their arguments. Instead, you can return a value from the function explicitly or require a pointer argument [excluded a code example] The increment(x) notation doesn't give a clue to the reader that x's value is being modified, the way x=next(x) and incr(&x) does. Consequently "plain" reference arguments should be used only where the name of the function gives a strong hint that the reference argument is modified.
-- Bjarne Stroustrup, The C++ Programming Language, Third edition
As mentioned in §5.5, functions that modify call-by-reference arguments can make programs hard to read and should most often be avoided [..] It can, however, be noticeable more efficient to pass a large object by reference than to pass it by value. In that case, the argument might be declared const to indicate that the reference is used for efficiency reasons only and not to enable the called function to change the value of the object [..]
-- Bjarne Stroustrup, The C++ Programming Language, Third edition
Yup, it's a fair copYes, when looking at the definition, it's plainly visible whether the function can change its argument. However, when seeing the function call, giving the address to the argument with the & operator shows clearly that the function isn't making a copy.