Re: problem incrementing my variable
- From: "J. J. Farrell" <jjf@xxxxxxxxxx>
- Date: Wed, 28 Jan 2009 01:24:22 +0000
Bartc wrote:
"Keith Thompson" <kst-u@xxxxxxx> wrote in message news:ln7i4g72xu.fsf@xxxxxxxxxxxxxxxxxxCBFalconer <cbfalconer@xxxxxxxxx> writes:Ian Collins wrote:[...]CBFalconer wrote:
Note that printf expects to receive a double. You should so cast
the argument. This is one of the few places that a C cast is
needed.
Isn't that taken care of by default argument promotion?
No, because printf doesn't know anything about the actual argument
presented. Its only identification is in the format string, which
doesn't have to be fixed. You can construct that format string
just before calling printf, for example. printf assumes arguments
have been promoted, but nothing does any promotion.
You are mistaken. This:
float f = 42.0;
printf("f = %f\n", f);
is perfectly correct code. The value of is is promoted, by the
default argument promotions, from float to double, which matches the
"%f" format. The default argument promotions include both the integer
promotions and promotion from float to double. See C99 6.5.2.2p6-7.
CBF might have a point, at least when int/double conversions are involved. This:
printf(s,i);
where i is an integer, and s *might* contain %d or %f, could cause a problem I think.
The programmer obviously has to make sure that the argument is of the type which he's told printf() to expect. If he's told it to expect a double by using %f, then he can give a double, or a float (which will be automatically converted to a double), or something cast to a double, or something cast to a float (which will then be automatically converted to a double), or any other expression which results in a float or a double.
If, at the time of writing the code, he doesn't know whether printf() will be using %f or %d at run-time, then he's stuffed - no casting of the argument will be correct for both cases.
.
- References:
- problem incrementing my variable
- From: Gary
- Re: problem incrementing my variable
- From: CBFalconer
- Re: problem incrementing my variable
- From: Ian Collins
- Re: problem incrementing my variable
- From: CBFalconer
- Re: problem incrementing my variable
- From: Keith Thompson
- Re: problem incrementing my variable
- From: Bartc
- problem incrementing my variable
- Prev by Date: Re: sequence points and the execution model
- Next by Date: Re: problem incrementing my variable
- Previous by thread: Re: problem incrementing my variable
- Next by thread: Re: problem incrementing my variable
- Index(es):
Relevant Pages
|