Re: printf("%d",float)



On 10 31 , 8 48 , candy_i...@xxxxxxxxx wrote:
Hi all,
I just came across the following program:

#include <stdio.h>
int main()
{
float a = 12.5;
printf("%d\n", a);
printf("%d\n", *(int *)&a);
return 0;
}

The program prints 0 and 1095237362. However, in my opinion it should
print 12 at both the places. Can anybody tell me where I am wrong?

hi, I help this test program will help you!

#include <stdarg.h>
#include <stdio.h>

// printf's action is like this
void test(char *fmt, ...)
{
int i;
float j;

va_list ap, app;

va_start(ap, fmt);
app = ap;

i = va_arg(ap, int); // when you call like printf("%d\n", i);
this line while be called

j = va_arg(app, double); // when you call like printf("%f\n", i);
this line while be called
// and you can't call it like j = va_arg(app,
float), because gcc compiler will complain

va_end(ap);

printf("if the args interpret as int, you get %d\n", i);
printf("it should interpret as double, the right answer is %f\n",
j);
}

int main(void)
{
float a = 12.5;

test("%d", a);

return 0;
}


below is define of va_arg, you can find it in <stdarg.h>

typedef char * va_list;

#define va_start _crt_va_start
+-- #define va_arg _crt_va_arg
| #define va_end _crt_va_end
|
| #define _crt_va_start(ap,v) ( ap = (va_list)_ADDRESSOF(v) +
_INTSIZEOF(v) )
+-> #define _crt_va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) -
_INTSIZEOF(t)) )
#define _crt_va_end(ap) ( ap = (va_list)0 )

.



Relevant Pages

  • Re: Abnormal program termination
    ... foo.c:4: warning: function declaration isn't a prototype ... Your version is legal under C90 rules, but int mainis more explicit ... float ave(), average; ...
    (comp.lang.c)
  • RTF Render with Scale
    ... float fHorzSizeInches = nHorzSize / 25.4f; ... IntPtr hdc = graphics.GetHdc; ... int nHorzSize = SafeNativeMethods.GetDeviceCaps(hdc, ... PHYSICALWIDTH = 110, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: RAD vs. performance
    ... work with both int and float. ... name (e.g. "+" for both int and float addition). ... Again, it's a compatibility issue. ... contend that assuming interfaces are equivalent and inferring the most ...
    (comp.lang.misc)
  • (part1b) Han from China teaches you C
    ... int flist, mlist, slist; ... float board_size; ... static void draw_tube(float bottom_radius, float top_radius, ... glVertex3f(xmin, ymin, zmax); glVertex3f; ...
    (comp.lang.c)
  • Re: RTF Render with Scale
    ... float fHorzSizeInches = nHorzSize / 25.4f; ... IntPtr hdc = graphics.GetHdc; ... int nHorzSize = SafeNativeMethods.GetDeviceCaps(hdc, ... PHYSICALWIDTH = 110, ...
    (microsoft.public.dotnet.languages.csharp)