beginner reference type parameter confusion [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
foo(int &bar)
{
bar = 5;
}
The call to this function would be
int foobar = 2;
foo(foobar);
Am I right in thinking that the function parameter essentially 'gets' the memory address of the variable, but does not then have to be dereferenced in foo, and that I would be changing the original value of foobar? Before this I was under the Impression that you would have to pass in a memory address like this:
foo(&foobar);
and then use the variable inside foo like this:
*bar = 5;
Am I right in thinking that this is wrong? I think, like a lot of beginners, the confusion came from thinking that a reference was like a pointer in that it held a memory address, but it's never really a type is it? Just an operator.

References are usually implemented with underlying pointers (although that is not mandated by the standard), but they are a totally different beast than pointers. A reference is simply a new name or alias for an existing variable. When you do
void foo(int& bar)
{
bar = 5;
}
int foobar = 2;
foo(foobar);
you are invoking foo to be evaluated with the variable foobar, so essentially bar within foo becames foobar. The usual compiler impementation for this is to actually implement this code like this:
void foo(int* bar)
{
*bar = 5;
}
int foobar = 2;
foo(&foobar);

If you did this:
void foo(int& bar) { bar = 6; }
int main() {
int x = 3;
foo(x);
}
x in main would equal 6. This is because a reference/alias (a different name for the same variable) is passed into foo. So, bar in function foo is the same variable as x in main, same memory location, and everything.
This is different from normal passing like this:
void foo(int bar) { bar = 6; }
int main() {
int x = 3;
foo(x);
}
where bar would be a new copy constructed value copied from x in main (note that copy constructor would better apply to a non-scalar type, but the idea is the same).
And lastly, if you did:
void foo(int* bar) { *bar = 6; }
int main() {
int x = 3;
foo(&x);
}
It would say "I want a pointer to an integer" for foo's parameter. In main, we take the "Address of stack variable x" which is in essence the same thing as a pointer to x, and we pass it into bar. Then dereferencing bar and assigning 6 to it would make x in main equal to 6 too :)

Related

why when a function takes a pointer, then we pass the address of a specific variable, and not a pointer?

for example :
void foo(int *ptr) {
some code///
}
int main() {
int x = 5;
foo(&x);
}
but not this :
void foo(int *ptr) {
some code///
}
int main() {
int x = 5;
int *ptr = &x
foo(ptr);
}
I read articles about this, but everything that says there is that "we are passing the address", but not a pointer, I can not understand why, please tell me
The following snippet is fine(legal/valid) because variable ptr is a pointer meaning it holds the address of an int(in this case). And this is exactly what foo expects as the type of its parameter.
void foo(int *ptr) {
// some code///
}
int main() {
int x = 5;
int *ptr = &x;//ptr is a pointer to an int
foo(ptr);//this works because foo expects a pointer to an int
}
Your example (after the modification)
int *ptr = &x
foo(ptr);
is perfectly valid and does exactly the same as foo(&x). The only difference is that you declare an extra variable of type int*. The compiler will typically optimize it away, so there's no real difference between the two.
A pointer holds the memory address of a variable. If a function takes a pointer, you are actually passing the address of the variable that it is pointing to so passing a pointer is actually passing an address. Both cases are legal and do the same thing.

Can we assign values to function?

Why the output is 30 here? And how fun()=30 is valid? What is meant by assigning function a value? And why removing static keyword throws segmentation fault?
#include<iostream>
using namespace std;
int &fun()
{
static int x = 10;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
Let's walk through your program step by step:
inside main() fun() is called.
fun() has a static variable x (static means, that x is stored in a special part of memory and not on the stack, so its value is preserved between function calls) (It's like having a global variable that is only visible from inside fun())
fun() returns a reference to x (references are almost like pointers)
You write to the returned reference of x, so x actually gets changed! (You don't write to the function)
now x is 30 and fun() returns 30 on the next call.
I hope this answers your first three questions.
Why you get a segmentation fault without the static keyword:
In this case x does exist on the stack. So whenever you call fun() some memory gets allocated on the stack to hold x. When fun() returns, this memory will be deallocated.
Now, the reference returned by fun(), will reference a piece memory, that is not allocated by your program anymore. In other words, the returned reference will reference a memory address, that does "not belong to your program", thus you are not allowed to write to it. And so you get a segmentation fault.
Can we assign values to function:
To answer the actual title of your question: Yes, we can, using function pointers:
int foo(int x) {
return x + 1;
}
int bar(int x) {
return x * 2;
}
void main() {
int(*f)(int) = foo;
// int the function pointed to returns an int
// (*f) f is the name of the function pointer
// (int) the function pointed to takes on int as paramter
// = foo; f now points to the function foo()
(*f)(3); // the same as foo(3), returns 4
f = bar; // now f points to bar()
(*f)(3); // the same as bar(3), returns 6
}
fun() returns a reference to static variable x, to which you assign the value 30. You don't assign anything to the function itself. In fact, it is not possible to assign anything to a function in C++.

What does "int& foo()" mean in C++?

While reading this explanation on lvalues and rvalues, these lines of code stuck out to me:
int& foo();
foo() = 42; // OK, foo() is an lvalue
I tried it in g++, but the compiler says "undefined reference to foo()". If I add
int foo()
{
return 2;
}
int main()
{
int& foo();
foo() = 42;
}
It compiles fine, but running it gives a segmentation fault. Just the line
int& foo();
by itself both compiles and runs without any problems.
What does this code mean? How can you assign a value to a function call, and why is it not an rvalue?
The explanation is assuming that there is some reasonable implementation for foo which returns an lvalue reference to a valid int.
Such an implementation might be:
int a = 2; //global variable, lives until program termination
int& foo() {
return a;
}
Now, since foo returns an lvalue reference, we can assign something to the return value, like so:
foo() = 42;
This will update the global a with the value 42, which we can check by accessing the variable directly or calling foo again:
int main() {
foo() = 42;
std::cout << a; //prints 42
std::cout << foo(); //also prints 42
}
All the other answers declare a static inside the function. I think that might confuse you, so take a look at this:
int& highest(int & i, int & j)
{
if (i > j)
{
return i;
}
return j;
}
int main()
{
int a{ 3};
int b{ 4 };
highest(a, b) = 11;
return 0;
}
Because highest() returns a reference, you can assign a value to it. When this runs, b will be changed to 11. If you changed the initialization so that a was, say, 8, then a would be changed to 11. This is some code that might actually serve a purpose, unlike the other examples.
int& foo();
Declares a function named foo that returns a reference to an int. What that examples fails to do is give you a definition of that function that you could compile. If we use
int & foo()
{
static int bar = 0;
return bar;
}
Now we have a function that returns a reference to bar. since bar is static it will live on after the call to the function so returning a reference to it is safe. Now if we do
foo() = 42;
What happens is we assign 42 to bar since we assign to the reference and the reference is just an alias for bar. If we call the function again like
std::cout << foo();
It would print 42 since we set bar to that above.
int &foo(); declares a function called foo() with return type int&. If you call this function without providing a body then you are likely to get an undefined reference error.
In your second attempt you provided a function int foo(). This has a different return type to the function declared by int& foo();. So you have two declarations of the same foo that don't match, which violates the One Definition Rule causing undefined behaviour (no diagnostic required).
For something that works, take out the local function declaration. They can lead to silent undefined behaviour as you have seen. Instead, only use function declarations outside of any function. Your program could look like:
int &foo()
{
static int i = 2;
return i;
}
int main()
{
++foo();
std::cout << foo() << '\n';
}
int& foo(); is a function returning a reference to int. Your provided function returns int without reference.
You may do
int& foo()
{
static int i = 42;
return i;
}
int main()
{
int& foo();
foo() = 42;
}
int & foo(); means that foo() returns a reference to a variable.
Consider this code:
#include <iostream>
int k = 0;
int &foo()
{
return k;
}
int main(int argc,char **argv)
{
k = 4;
foo() = 5;
std::cout << "k=" << k << "\n";
return 0;
}
This code prints:
$ ./a.out
k=5
Because foo() returns a reference to the global variable k.
In your revised code, you are casting the returned value to a reference, which is then invalid.
In that context the & means a reference - so foo returns a reference to an int, rather than an int.
I'm not sure if you'd have worked with pointers yet, but it's a similar idea, you're not actually returning the value out of the function - instead you're passing the information needed to find the location in memory where that int is.
So to summarize you're not assigning a value to a function call - you're using a function to get a reference, and then assigning the value being referenced to a new value. It's easy to think everything happens at once, but in reality the computer does everything in a precise order.
If you're wondering - the reason you're getting a segfault is because you're returning a numeric literal '2' - so it's the exact error you'd get if you were to define a const int and then try to modify its value.
If you haven't learned about pointers and dynamic memory yet then I'd recommend that first as there's a few concepts that I think are hard to understand unless you're learning them all at once.
The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".
In your example, foo is clearly returning an lvalue based on the signature, but you return an rvalue that is converted to an lvalue. This clearly is determined to fail. You could do:
int& foo()
{
static int x;
return x;
}
and would succeed by changing the value of x, when saying:
foo() = 10;
The function you have, foo(), is a function that returns a reference to an integer.
So let's say originally foo returned 5, and later on, in your main function, you say foo() = 10;, then prints out foo, it will print 10 instead of 5.
I hope that makes sense :)
I'm new to programming as well. It's interesting to see questions like this that makes you think! :)

c++ how to point to a member of an array

Wondering how to assign a pointer to an array member:
struct foo {
int INT;
}
int main() {
foo bar[10];
foo *baz;
baz = bar[5];
}
This does not work, but I am wondering what would.
Thank you much for any help.
You want to do baz = &bar[5];. bar[5] Refers to the 6th foo object instance itself, so just take the address (with the & operator) to assign to the pointer, same as any other situation;
Alternatively, you can also do baz = (bar + 5); since here bar used without a number is a pointer to the first element and +5 gives the 6th element.

C++: is return value a L-value?

Consider this code:
struct foo
{
int a;
};
foo q() { foo f; f.a =4; return f;}
int main()
{
foo i;
i.a = 5;
q() = i;
}
No compiler complains about it, even Clang. Why q() = ... line is correct?
No, the return value of a function is an l-value if and only if it is a reference (C++03). (5.2.2 [expr.call] / 10)
If the type returned were a basic type then this would be a compile error. (5.17 [expr.ass] / 1)
The reason that this works is that you are allowed to call member functions (even non-const member functions) on r-values of class type and the assignment of foo is an implementation defined member function: foo& foo::operator=(const foo&). The restrictions for operators in clause 5 only apply to built-in operators, (5 [expr] / 3), if overload resolution selects an overloaded function call for an operator then the restrictions for that function call apply instead.
This is why it is sometimes recommended to return objects of class type as const objects (e.g. const foo q();), however this can have a negative impact in C++0x where it can inhibit move semantics from working as they should.
Because structs can be assigned to, and your q() returns a copy of struct foo so its assigning the returned struct to the value provided.
This doesn't really do anything in this case thought because the struct falls out of scope afterwards and you don't keep a reference to it in the first place so you couldn't do anything with it anyway (in this specific code).
This makes more sense (though still not really a "best practice")
struct foo
{
int a;
};
foo* q() { foo *f = new malloc(sizeof(foo)); f->a = 4; return f; }
int main()
{
foo i;
i.a = 5;
//sets the contents of the newly created foo
//to the contents of your i variable
(*(q())) = i;
}
One interesting application of this:
void f(const std::string& x);
std::string g() { return "<tag>"; }
...
f(g() += "</tag>");
Here, g() += modifies the temporary, which may be faster that creating an additional temporary with + because the heap allocated for g()'s return value may already have enough spare capacity to accommodate </tag>.
See it run at ideone.com with GCC / C++11.
Now, which computing novice said something about optimisations and evil...? ;-].
On top of other good answers, I'd like to point out that std::tie works on top of this mechanism for unpacking data from another function. See here. So it's not error-prone per se, just keep in mind that it could be a useful design pattern