Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 816
Sossisos Avatar asked Oct 19 '22 17:10

Sossisos


People also ask

What it means to int?

Summary of Key Points "Isn't it" is the most common definition for INT on Snapchat, WhatsApp, Facebook, Twitter, Instagram, and TikTok. INT. Definition: Isn't it.

What does int mean over text?

Idk is an abbreviation of the phrase I don't know. Idk is part of the newly developed dialect called text speak or SMS language. This dialect is mostly used in informal communication, and especially when communicating via text messages or instant messages. The phrase idk has been part of text speak since at least 2002.

What does int [] mean in C#?

int is a keyword that is used to declare a variable which can store an integral type of value (signed integer) the range from -2,147,483,648 to 2,147,483,647. It is an alias of System.

What is the full word for int?

int , short for integer in many programming languages.


Video Answer


1 Answers

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
}
like image 175
TartanLlama Avatar answered Oct 21 '22 07:10

TartanLlama