473,785 Members | 2,363 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Typecasting in C

Hi,
Whenever we type in this code
int main()
{
printf("%f",10) ;
}
we get an error. We can remove that by using #pragma directive t
direct that to the 8087. Even after that the output is 0.00000 and no
10.0000. Can anybody tell me why it is like that and why typecasting i
not done in this case?
-
andynai
-----------------------------------------------------------------------
Posted via http://www.codecomments.co
-----------------------------------------------------------------------

Nov 14 '05 #1
63 3419
andynaik wrote:
Hi,
Whenever we type in this code
int main()
{
printf("%f",10) ;
}
we get an error. We can remove that by using #pragma directive to
direct that to the 8087. 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??


%f is for double, but 10 is an int.

Rewrite as:
#include <stdio.h>
int main(){printf(" %d",10);retur n 0;}
or as:
#include <stdio.h>
int main(){printf(" %f",10.0);retur n 0;}

- Dario
Nov 14 '05 #2
"andynaik" <an************ *@mail.codecomm ents.com> wrote in message
news:2e******** *************** *******@news.th enewsgroups.com ...
Whenever we type in this code
int main()
{
printf("%f",10) ;
}
we get an error. We can remove that by using #pragma directive to
direct that to the 8087.
Means nothing to me (compiler specifics are off-topic here).
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??


Read section 15 in the FAQ. Post back if you still have questions.
http://www.eskimo.com/~scs/C-faq/s15.html

Alex
Nov 14 '05 #3
In 'comp.lang.c', andynaik <an************ *@mail.codecomm ents.com> wrote:
Hi,
Whenever we type in this code
int main()
{
printf("%f",10) ;
}
we get an error.


Compiling MAIN.C:
Warning MAIN.C 4: Call to function 'printf' with no prototype
Warning MAIN.C 5: Function should return a value
Linking EXE\PROJ.EXE:

This code invokes an undefined behaviour (UB). It is mandatory to supply a
prototype when using a variadic function. Add

#include <stdio.h>

That said, 10 is a int. "%f" is expecting a double. If you want to printf a
double, use 10.0, or the (double) typecast.

Finally, some old Borland C compilers anre buggy and forget to link the
floating point library un such a case. This little hack can help:

#include <stdio.h>

#ifdef __BORLANDC__
/* The pesky "floating point formats not linked" killer hack : */
extern unsigned _floatconvert;
#pragma extref _floatconvert
#endif

int main (void)
{
printf ("%f\n", 10.0);

return 0;
}

--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #4

"Alex Fraser" <me@privacy.net > a écrit dans le message de
news:2k******** ***@uni-berlin.de...
"andynaik" <an************ *@mail.codecomm ents.com> wrote in message
news:2e******** *************** *******@news.th enewsgroups.com ...
Whenever we type in this code
int main()
{
printf("%f",10) ;
}
we get an error. We can remove that by using #pragma directive to
direct that to the 8087.


Means nothing to me (compiler specifics are off-topic here).
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??


Read section 15 in the FAQ. Post back if you still have questions.
http://www.eskimo.com/~scs/C-faq/s15.html

Alex


The FAQ should mention that some compilers DO test the arguments
for sprintf/printf/fprintf etc for validity.

This CAN be done. lcc-win32 does it, and other compilers too.

For instance the above code produces
Warning tx.c: 4 printf argument mismatch for format f. Expected double got
int
0 errors, 1 warnings
Nov 14 '05 #5
Some compilers DO test the arguments of printf for
validity.
Under lcc-win32 the above code produces:

Warning tx.c: 4 printf argument mismatch for format f. Expected double got
int
0 errors, 1 warnings
Nov 14 '05 #6
In <cb**********@n ews-reader3.wanadoo .fr> "jacob navia" <ja***@jacob.re mcomp.fr> writes:

The FAQ should mention that some compilers DO test the arguments
for sprintf/printf/fprintf etc for validity.

This CAN be done.
ONLY if the compiler can "see" the contents of the format string.
Which is usually the case, but exceptions are not that rare either.

At some point, gcc had the annoying habit of warning if it couldn't
perform such a check (if enabled), because the format was not a
string literal.
lcc-win32 does it, and other compilers too.
Other compilers do a much better job than lcc-win32, when it comes to
format string consistency checks. See below.
For instance the above code produces
Warning tx.c: 4 printf argument mismatch for format f. Expected double got
int
0 errors, 1 warnings


OTOH, lcc-win32 silently accepts printf("%d\n", "foo"), which is very
bad, considering the relative positions of the D and S keys on most
keyboard layouts (i.e. it is a fairly frequent mistake to type d
when you mean s).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #7

"Dan Pop" <Da*****@cern.c h> a écrit dans le message de
news:cb******** **@sunnews.cern .ch...
OTOH, lcc-win32 silently accepts printf("%d\n", "foo"), which is very
bad, considering the relative positions of the D and S keys on most
keyboard layouts (i.e. it is a fairly frequent mistake to type d
when you mean s).


I pondered a long time about that one, since it is perfectly legal to
do:

char *p;
....

printf("The address is %d\n",p);

specially in debugging code.

Granted, this is weird, but how to discriminate between
legal and wrong usage?

But maybe you are right. I added a warning when the "d" format
is used with a pointer.

The "x" format will NOT provoke any warnings.

But this is at the limit of what a compiler can do.

Nov 14 '05 #8
In <cb**********@n ews-reader1.wanadoo .fr> "jacob navia" <ja***@jacob.re mcomp.fr> writes:

"Dan Pop" <Da*****@cern.c h> a écrit dans le message de
news:cb******* ***@sunnews.cer n.ch...
OTOH, lcc-win32 silently accepts printf("%d\n", "foo"), which is very
bad, considering the relative positions of the D and S keys on most
keyboard layouts (i.e. it is a fairly frequent mistake to type d
when you mean s).
I pondered a long time about that one, since it is perfectly legal to
do: ^^^^^^^^^^^^^^^ ^^^

char *p;
...

printf("The address is %d\n",p);


What have you been smoking recently?
specially in debugging code.

Granted, this is weird, but how to discriminate between
legal and wrong usage? ^^^^^
Can I have a chapter and verse? When did they drop the following
paragraph from the C standard?

9 If a conversion specification is invalid, the behavior is
undefined. If any argument is not the correct type for the
corresponding conversion specification, the behavior is undefined.

What is the type expected by %d? What is the type of p?
So, the legal usage would be (int)p instead of a plain p, right?
But maybe you are right. I added a warning when the "d" format
is used with a pointer.

The "x" format will NOT provoke any warnings.
Which is just as bad, especially given that x is also a typo candidate
for s.
But this is at the limit of what a compiler can do.


In your humble opinion, what is the purpose of the %p conversion
specification? Why support *anything else* for displaying pointer values?

And if a user *really* wants to use the extra flexibility of the
signed or unsigned integer conversion descriptors, what is preventing
him from casting the pointer to the desired type?

As I said in other threads, you have nothing to lose by using gcc's
behaviour as a guide. If you can benefit from the thought many competent
people have put into the same issue, why reinvent the wheel?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #9
andynaik wrote:
Hi,
Whenever we type in this code
int main()
{
printf("%f",10) ;
}
we get an error. We can remove that by using #pragma directive to
direct that to the 8087. 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??


Because you forgot
#include <stdio.h>
You also forgot to terminate the last line of output with an end-of-line
character.

The first mistake, omission of the prototype for a variadic function, is
always an error. The second is an error in code designed to be
portable, and may result in behavior you were not expecting.
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
8186
by: Kapil Khosla | last post by:
Hi, I have been trying to understand this concept for quite sometime now somehow I am missing some vital point. I am new to Object Oriented Programming so maybe thats the reason. I want to understand what is typecasting in C++. Say I have a Base class and a Derived class, I have a pointer to an object to each. Base *ba = new Base; Derived *de = new Derived;
7
4545
by: Nicolay Korslund | last post by:
Hi! I'm having a little trouble with the typecast operator, can anybody help me with the rules for when the this operator is invoked? In the class 'Test' in the code below, the typecast operator returns a 'mytype'. In main() I use the operator on 'Test'-class objects. If 'mytype' is a pointer the operator works fine. But if I instead try to call an overloaded operator, the typecast operator is not invoked, and I get a compiler error...
2
4180
by: Arun Prasath | last post by:
Hi all, I have the following question regd pointer typecasting. Is the following type of pointer typecasting valid? #define ALLOC(type,num) ((type *)malloc(sizeof(type)*num)) /*begin code*/
11
4425
by: Vinod Patel | last post by:
I have a piece of code : - void *data; ...... /* data initialized */ ...... struct known_struct *var = (struct known_struct*) data; /*typecasting*/ How is this different from simple assignment. int b = some_value;
3
1646
by: jdm | last post by:
In the sample code for the SortedList class, I see the use of a string typecasting macro consisting of a single letter "S". i.e.: Sortedlist->Add(S"Keyval one", S"Item one"); Now I have deduced that the "S" can be replaced with (String __gc *) and the code will compile and run just fine. But what I can't find is what exactly Microsoft calls these macros (I have also seen "L" used the same way) and where they are all documented. I...
7
2187
by: Raghu | last post by:
Hello All, I need some help regarding overloading operation. Is there any way to overload typecasting? I mean if i have a piece of code as below. int a = 2: float b; b = (float)a;
16
10400
by: Abhishek | last post by:
why do I see that in most C programs, pointers in functions are accepted as: int func(int i,(void *)p) where p is a pointer or an address which is passed from the place where it is called. what do you mean by pointing to a void and why is it done? Aso, what happens when we typecast a pointer to another type. say for example int *i=(char *)p; under different situations? I am kind of confused..can anybody clear this confusion by clearly...
4
7746
by: vivekian | last post by:
Hi, This is the part of the code am trying to compile to : void Server::respondToClient ( std::string response ) { .... .... if ((numbytes = sendto ( sockFd_ , response , sizeof(response) , 0, (struct sockaddr *)&clientAddr, sizeof (clientAddr))) == -1){
12
4481
by: bwaichu | last post by:
What is the best way to handle this warning: warning: cast from pointer to integer of different size I am casting in and out of a function that requires a pointer type. I am casting an integer as a pointer, but the pointer is 8 bytes while the integer is only 4 bytes. Here's an example function:
0
9485
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10356
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10098
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8986
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6743
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5390
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5523
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4058
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2890
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.