my first program

hi could you please say what is wrong or missing witth this code .why is area always 0

#include <iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;

double const & calc(int);
int main(){

const int lim=3;
int dizi[lim]={1,2,3};
for(int k=0;k<3;k++){
cout<< "area "<< calc(dizi[1])<<endl;
}


system("PAUSE");
return EXIT_SUCCESS;
}
double const & calc(int i){

return i*i;
}
Because you're returning a reference to something that is destroyed as soon as the function calc finishes.

Don't return a reference to something that no longer exists. Just return a value.

1
2
3
double calc(int i){
return i*i;
}
calc returns a reference to a temporary object you get from i*i. The problem is that this temporary object will only exist on that line. It will not exist outside the function. So what calc actually returns is a reference to some non existing object.

There is no reason to return a reference here. Just return a normal double.
@digrev

Also, you'll be returning the same number, each time, since you are always sending dizi[1]; to the function, instead of using dizi[k];
thank you but i dont understand what is destroyed my friend what do you mean here

"Don't return a reference to something that no longer exists".
1
2
3
4
double const & calc(int i){

return i*i;
}


At this line here
return i*i;
a value is calculated - i*i. That value exists somewhere in memory. When you return a reference (which is what you're doing with that &) what gets returned is not a copy of that value - it is that actual value, at that place in memory.

However, when a function finishes, anything you made inside that function (apart from anything you made using new, but that's not relevant here) is destroyed. All the memory that was used by that function is tidied up and made available for something else to use. So what happened to the value you returned? It no longer exists. This is a big problem if you try to use it - using values that don't exist any more is not a good idea.
Last edited on
thanks a lot friends i was trying to understand reference thing .is it possible to do same thing with references
Last edited on
Topic archived. No new replies allowed.