[vox-tech] totally confused about C promotion

Joel Baumert vox-tech@lists.lugod.org
Mon, 14 Jan 2002 16:51:23 -0800


I'll take a shot at this.  The prototype for sqrt is:

double sqrt(double x);

and for printf is:

int printf(const char *format, ...);

The problem is the "..." makes it so any type can follow.  The
specification has specific rules about what is promoted and what
isn't.  From what I remember, shorts -> ints and floats go to
doubles.  

In your example program your format specifier is telling the 
compiler to accept a long double, but you are only passing it
a double which is fixed by your cast.  For most compilers it
would be your problem to figure out what is wrong, but I think
that gcc is smart about printf and should throw a warning when
you have a type mismatch between the format specifier and the
parameter.  Are you compiling with -Wall?

Joel


On Mon, Jan 14, 2002 at 03:16:18PM -0800, Peter Jay Salzman wrote:
> from kernighan and ritchie, page 45:
> 
>   For example, the library routine sqrt expects a double argument, and
>   will produce nonsense if inadvertantly handed something else.
> 
> consider the following code1.c:
> 
>    int main(void)
>    {
>    	long double var = 4.0L;
>    
>    	printf("%Lf\n", sqrt(var));
>    	return 0;
>    }
> 
> this prints nonsense (0.0000), since sqrt returns double and i'm
> printing a long double.  next, consider this code2.c:
> 
>    int main(void)
>    {
>    	long double var = 4.0L;
>    
>    	printf("%Lf\n", (long double)sqrt(var));
>    	return 0;
>    }
> 
> this works.  but i'm not really interested in just "working" because
> this particular code is extremely important to me.  i don't want to base
> my code on something that works by accident.
> 
> what happens when you hand a long double to a math function which
> expects a double?  i can't find any rules for "demotion" in K+R.
> does code2.c work by accident or is there a concept of demoting floating
> points to a narrower width when the function expects them to be
> narrower?
> 
> pete
> 
> -- 
> The mathematics [of physics] has become ever more abstract, rather than more
> complicated.  The mind of God appears to be abstract but not complicated.
> He also appears to like group theory.  --  Tony Zee's `Fearful Symmetry'
> 
> PGP Fingerprint: B9F1 6CF3 47C4 7CD8 D33E  70A9 A3B9 1945 67EA 951D
> _______________________________________________
> vox-tech mailing list
> vox-tech@lists.lugod.org
> http://lists.lugod.org/mailman/listinfo/vox-tech