float functions

Walter L. Peterson, Jr. wlp at calmasd.GE.COM
Wed Aug 3 02:07:53 AEST 1988


In article <7441 at cit-vax.Caltech.Edu>, gtchen at tybalt.caltech.edu (George T. Chen) writes:
> 
> How do I get c to recognize a function as returning a float and not
> a double?  It seems the moment I declare something as a function, the
> compiler cast it as double.  I am primarily using sizeof to determine
> the type.
> 
> Here is a sample code.
> 
> float f1()
> {  return( (float) 10.0);
> }
> 
> main()
> {  float f1(), res;
>    res = f1();
>    printf("sizeof f1() is %d\n",sizeof(f1()));
>    printf("sizeof res is %d\n",sizeof(res));
> }
> 
> This program invariable returns 8 and 4, not 4 and 4.   Help.
> 

The results that you get, 8 and 4, while not correct are incorrect
for a different reason than the type of the function return value.

The local variable, res is 4 bytes, since you have declared it to be
float. In this case all is as it should be.  You are, however, expecting
that the sizeof value for f1() will also be 4 bytes; this is
incorrect.

In paragraph A7.4.8 Sizeof Operator (p204 in K&R 2ed.) it states:

   "The sizeof operator yields the number of bytes required to store
    an object of the type of its operand....The operator may not be
    applied to an operand of function type, or of incomplete type or
    to a bit-field."

Since the Second Edition of K&R follows the proposed ANSI standard and
your compiler may not, what I suspect is happening is that your
compiler's version of sizeof is returning the number of bytes in a
POINTER TO A FUNCTION, which could very well BE 8 bytes on your system.

In any case, a function is an inappropriate operand for the sizeof
operator and so you should not use it even if your compiler lets you
(if your compiler claims to be ANSI std. then I would say that this is
a bug in the compiler). 

So, don't worry. If you declare f1() as returning a float, it will
return a float.

-- 
Walt Peterson   GE-Calma San Diego R&D
"The opinions expressed here are my own and do not necessarily reflect those
GE, GE-Calma nor anyone else.
...{ucbvax|decvax}!sdcsvax!calmasd!wlp        wlp at calmasd.GE.COM



More information about the Comp.lang.c mailing list