Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a functions return an int, can an int be assigned to it?

If a function returns an int, can it be assigned by an int value? I don't see it makes too much sense to assign a value to a function.

int f() {}

f() = 1;

I noticed that, if the function returns a reference to an int, it is ok. Is it restricted only to int? how about other types? or any other rules?

int& f() {}

f() = 1;
like image 993
skydoor Avatar asked Feb 07 '10 13:02

skydoor


People also ask

Can a function return an integer?

In addition to passing data to functions, you can have functions return data. They can return a single data item—an integer, for example—or an array or an object.

Can you assign a value to a function?

No, you can't assign values to functions. You can assign values to function pointers, but not to functions in C++. Try assigning anything to foo in your example, for instance.

Can a'int be a function?

The int() function returns the numeric integer equivalent from a given expression. Expression whose numeric integer equivalent is returned. This example truncates the decimal and returns the integer portion of the number. This example illustrates using the int() function to keep one decimal place and truncate the rest.

Which function always returns an integer value?

Yes, main() must return int . The return value is passed back to the operating system, to indicate whether the program ran successfully: zero means success.


2 Answers

The first function returns an integer by-value, which is an r-value. You can't assign to an r-value in general. The second f() returns a reference to an integer, which is a l-value - so you can assign to it.

int a = 4, b = 5;

int& f() {return a;}

...
f() = 6;
// a is 6 now

Note: you don't assign a value to the function, you just assign to its return value. Be careful with the following:

int& f() { int a = 4; return a; }

You're returning a reference to a temporary, which is no longer valid after the function returns. Accessing the reference invokes undefined behaviour.

like image 197
Alexander Gessler Avatar answered Sep 28 '22 12:09

Alexander Gessler


  • What are Lvalues and Rvalues? by Danny Kalev
  • Lvalues and Rvalues by Dan Saks
  • Lvalues and Rvalues by Mikael Kilpeläinen
like image 39
just somebody Avatar answered Sep 28 '22 12:09

just somebody