[vox-tech] totally confused about C promotion

Rod Roark vox-tech@lists.lugod.org
Mon, 14 Jan 2002 15:41:42 -0800


It's not sqrt that is producing nonsense, but rather printf.  Printf 
accepts any types in its arguments, and it's your responsibility to make 
sure that the data types match up with what's in the format string.  The 
compiler can't fix it because it's a runtime issue.

This is generally considered a weakness in the way that printf works.

Regarding the math function, the compiler can cast the argument (perhaps 
with a warning) because it knows how sqrt is declared.

Hope this helps....

-- Rod
   http://www.sunsetsystems.com/

On Monday 14 January 2002 15:16, 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