Hello everyone !
I am still a beginner, and am posting the code in which I have problems -
I compiled it in VC++ 6.0 standard edition, and it gave two warnings and no errors. The warnings disappear if i use double everywhere instead of float.
the warning (same twice)-
warning C4305: '=' : truncation from 'const double ' to 'float '
#include<stdio.h>
#include<conio.h>
float fun1(float,float);
float *fun2(float,float);
int *fun3(int,int);
void main()
{
float i,j,k,prod,*l;
int o=3,m=2,*n;
i=7.56;
j=3.39;
k=fun1(i,j);
l=fun2(i,j);
n=fun3(o,m);
prod=i*j;
printf("the product =\n\n%f",prod);
printf("\n\nthe product(from function -call by value-return value) = %f",k);
printf("\n\nThe product (from function -call by value-return pointer)= %f",*l);
printf("\n\nThe product of integers -return pointer= %d",*n);
}
float fun1(float i,float j)
{
float prod;
prod=i*j;
return prod;
}
float *fun2(float i, float j)
{
float *p,prod;
prod=i*j;
p=∏
return p;
}
int *fun3(int i,int j)
{
int prod,*p;
prod=i*j;
p=∏
return p;
}
I have three questions -
1. If i use float instead of double, i get the answer 25.628401 (which is wrong(-ish), the answer is 25.628400)
2. the first two printf's give the right result, but the last two printf's give the wrong result. the second printf gives 0.000000 and the last printf gives a garbage six digit value.
3. if i replace "return p" by "return &prod" in fun2, VC++ gives a warning
warning C4172: returning address of local variable or temporary
I understand that after control in fun2 or fun3 ends, the local variables "die" and if i use static, i get the right answer, but why is this happening ?
When a variable is declared, a memory "cell" is allocated to it and the name (say i) is given to it. Here, after the control exits from the functions (fun2 or fun3), the memory cell has lost its name(which was "i " till the control was in fun2 or fun3), but the address of the cell remains the same, so i shud be able to access it correctly using pointers. It is happening as if the compiler resets the value of the memory cell (to zero if earlier it was float and garbage if it was int) as soon as the memory cell loses its name. And if this is happening (by any chance), why is the compiler doing this ??
I appreciate any help you can give......