-
problem with functions
I can run the following program
Code:
#include<stdio.h>
main()
{
int i,j;
printf("enter number \n");
scanf("%d",&i);
j=we(i);
printf("%d",j);
}
int we(int a)
{
a=a+1;
return a;
}
It does not have a function prototype but it works
But I applied the same concept in using arrays accessing a function which takes a float as an input and produces a float as an out put it is as follows
Code:
#include<stdio.h>
#define p 3.14
main()
{
int n,i=0;
float rad[100],area[100];
printf("enter rad\n");
printf(" rad?\n");
scanf("%f",&rad[i]);
while(rad[i])
{
if (rad[i]<0)
area[i]=0;
else
area[i]=process(rad[i]);
printf(" rad2?\n");
scanf("%f",&rad[++i]);
}
n=--i;
printf("summary of results\n");
for (i=0;i<=n;++i)
printf("rad = %f area = %f\n",rad[i],area[i]);
}
float process(float r2)
{
float a;
a=p*r2*r2;
printf("%f",a);
return (a);
}
But this program compiles but does not calculate the value
a=p*r2*r2;
because when I checked inside PROCESS the r2’s value=0
can anybody help me please?
Thanks in advance
-
There's almost no reason at all not to use prototypes. They've been standard since 1989. Using prototypes (properly) will fix your problems, as I assume you know.
At any rate, if you don't use a prototype, the compiler will assume your function looks like:
The int of course means it returns an int. The () means the arguments are unspecified. One side-effect of this is that arguments are subject to the default argument promotions. The upshot in this case is that floats are promoted to doubles. Your function (whose definition contains a prototype) says it expects a float as an argument, but that's not possible. Any float, due to the lack of a prototype at the time of the function call, will be passed as a double.
The same problem rears its head in the return value, too: the compiler thinks your function returns an int, but it doesn't. That's a problem. Even in the K&R days you needed to declare functions that returned something other than int, and today you should not only declare, but prototype. The reason your first example worked is because it returned an int (which the compiler assumed) and it was passed an int (which isn't promoted in the absence of a prototype: an int stays an int).
To make a long story short: Use prototypes. List prototypes before you call functions. Be happy.