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;
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With