-3
double midpoint(const double &a, const double &b){
    /*code*/ 
}
int main(){
    double x=midpoint(1,2);
    cout << x << endl;
}

Now in the function argument, I use call by reference. But in call by reference original variable is modified. But here, I use function argument as numbers themselves. Then in which memory space are there values stored?

Also, note that in this case, the code gives an error (invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int').

So what exactly is the functioning of const part?

double midpoint(double &a, double &b){
    /*code*/ 
}
int main(){
    double x=midpoint(1,2);
    cout << x << endl;
}
Aditya Agarwal
  • 221
  • 2
  • 11

1 Answers1

1

Patronisingly, this is a tricky corner of the language for beginners. Note first that the memory part is not really relevant insofar that the language specification doesn't really talk about it - it's a choice a compiler can make for itself.

The arguments (1 and 2) of midpoint(1, 2); are literals. These are allowed to bind (informally speaking, matched up) to const references, but not references. Hence

double midpoint(const double &a, const double &b)

can be called with literals but

double midpoint(double &a, double &b)

can't. To make matters worse, some compilers allow reference-binding as a language extension!

Finally, note there isn't really too much point in passing a double by const reference (sometimes it can be useful to prevent type conversions at calling sites); simply pass it by value instead:

double midpoint(double a, double b)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • But what about the memory part? And functioning of const, just a brief answer? – Aditya Agarwal Oct 10 '18 at 07:30
  • [after your last edit] Exactly! But then whats the difference between pass by const reference and normal pass by value? – Aditya Agarwal Oct 10 '18 at 07:31
  • @AdityaAgarwal: On your most recent comment, passing by const reference forbids implicit conversions at call sites. – Bathsheba Oct 10 '18 at 07:31
  • In this case, when the argument is value (literal, as you say) itself, then it cannot be converted in either case, can it? And thus I just want to know what is the difference in inner workings in both cases (pass by value and pass by const reference). That is, where are the values stored in both cases? – Aditya Agarwal Oct 10 '18 at 07:34
  • @AdityaAgarwal: That's down to a specific compiler. They might not be stored anywhere: the compiler might choose to inline a function, for example. But if you want to know more, Google "calling conventions". – Bathsheba Oct 10 '18 at 07:36
  • Have fun at https://godbolt.org/ and observe assembly output. The compiler can optimize the call altogether, so there's no difference. The compiler can remove the function, because it has no side effects. The "memory part" is depends on the compiler and how it chooses to optimize that function. – KamilCuk Oct 10 '18 at 07:37