Typecasting in C

M

Mark McIntyre

Hi,
Whenever we type in this code
int main()
{
printf("%f",10);
}
we get an error.

Yes, because the code is broken.
We can remove that by using #pragma directive to
direct that to the 8087.

Don't do that, you're breaking it even worse.
Even after that the output is 0.00000 and not
10.0000. Can anybody tell me why it is like that and why typecasting is
not done in this case??

This has nothing to do with typecasting. You're calling printf() without
any prototype or declaration in scope, so it has no idea what the arguments
mean. You absolutely must declare functions before you use them, typically
by #including the correct header.
 
K

Keith Thompson

Mark McIntyre said:
Whenever we type in this code
int main()
{
printf("%f",10);
}
we get an error.

Yes, because the code is broken. [...]
This has nothing to do with typecasting. You're calling printf() without
any prototype or declaration in scope, so it has no idea what the arguments
mean. You absolutely must declare functions before you use them, typically
by #including the correct header.

Including the <stdio.h> header to declare printf() won't solve this
problem (though of course you should do it anyway). For a function
that takes a variable number of arguments, the compiler still doesn't
know the types of the variable arguments. You have to make sure the
types of the arguments match the expected types for the format.

Some compilers may issue warnings based on the format string (if it's
a literal), but they won't do the conversions for you.

(BTW, Mark, your newsfeed.com sig is appearing twice on each post.)
 
E

Emmanuel Delahaye

jacob navia said:
printf("the address is: 0x%x\n",p);

where p is some pointer appears in several million lines in
existing code.

But it's wrong. On a x86 platform, it will fail in large memory model (at
least).

#include <stdio.h>

int main (void)
{
int a;
int *p = &a;

printf ("addr = %x\n", p);
printf ("addr = %p\n", (void *) p);
return 0;
}

Memory model small

D:\CLC\E\EMMANUEL>bc proj.prj
addr = fff4
addr = FFF4

Memory model large

D:\CLC\E\EMMANUEL>bc proj.prj
addr = ffe
addr = 8FF0:0FFE
 
E

Emmanuel Delahaye

Arthur J. O'Dwyer said:
Who's been using "%d" or "%x" to print *pointer* values?

I probably did in the earliest times, but not since I have used BC 3.1
(1991). I have learnt about the (void*) thing by reading c.l.c since 1999.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top