473,796 Members | 2,609 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
63 3421
In <cb**********@n ews-reader3.wanadoo .fr> "jacob navia" <ja***@jacob.re mcomp.fr> writes:
The expression

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

where p is some pointer appears in several million lines in
existing code.
If you think that the amount of existing broken code can prove anything,
you're sorely mistaken. The days when all the world was a 32-bit
platform are gone...
The warnings can become a nuisance and people would stop
using this feature. Personally I think warnings should be
kept to the essential ones, warnings that would uncover a
possible error.
In your stupidity, you don't realise that this is a genuine error, it
just doesn't manifest on *your* platform. Try to engage your brain
and think about platforms with 32-bit int's and 64-bit pointers
(increasingly common since DEC released Alpha OSF/1 in 1992).

To show you that the issue is *real* and not invented ad-hoc:

lx64:~/tmp 11> uname -m
x86_64
lx64:~/tmp 12> cat test.c
#include <stdio.h>

int main(void)
{
int i;
printf("%#x %p\n", &i, (void *)&i);
return 0;
}

lx64:~/tmp 13> gcc test.c
lx64:~/tmp 14> ./a.out
0xbffff00c 0x7fbffff00c
lx64:~/tmp 15> gcc -Wall test.c
test.c: In function `main':
test.c:6: warning: unsigned int format, pointer arg (arg 2)

As you can see, the two values are different: %x has lost information.
So, the people developing their code on your compiler will have a bad
surprise when trying to use it elsewhere and you believe that you're
doing them a favour!
Strictly speaking you should use %p, but I have almost
never seen it in debugging code, where this conversion is
used.

To the contrary of your expectations, I work to make a usable
compiler, not one that will please the purists around c.l.c


If you think you're doing your users any service by not diagnosing
their genuine mistakes, simply because they *accidentally* work on
your platform, you're even more stupid than I thought. People like you
have no business messing with compilers and libraries.

The FAQ *should* contain the following question: "Why should I avoid
lcc-win32 like the plague?". But the answer would significantly increase
its current size...

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

On Tue, 29 Jun 2004, jacob navia wrote:

The expression
printf("the address is: 0x%x\n",p);
where p is some pointer appears in several million lines in
existing code.


Has anyone besides Jacob ever seen this construct (or anything
similar) in real-world code? I've never encountered it. The
usual idiom in my part of the universe is more like

printf("(%d) %p\n", p!=NULL, (void*)p);

which has the benefit of (a) telling you something useful, and
(b) being standard, warning-less C code.

Who's been using "%d" or "%x" to print *pointer* values?

-Arthur
Nov 14 '05 #22
Arthur J. O'Dwyer <aj*@nospam.and rew.cmu.edu> wrote:
On Tue, 29 Jun 2004, jacob navia wrote:

The expression
printf("the address is: 0x%x\n",p);
where p is some pointer appears in several million lines in
existing code.
Has anyone besides Jacob ever seen this construct (or anything
similar) in real-world code? I've never encountered it. The
usual idiom in my part of the universe is more like printf("(%d) %p\n", p!=NULL, (void*)p); which has the benefit of (a) telling you something useful, and
(b) being standard, warning-less C code. Who's been using "%d" or "%x" to print *pointer* values?


It is quite common in legacy code. Especially in the stuff that
got carried over from the pre-ANSI days.

--
Alex Monjushko (mo*******@hotm ail.com)
Nov 14 '05 #23
On Tue, 29 Jun 2004, Arthur J. O'Dwyer wrote:

AJO>
AJO>On Tue, 29 Jun 2004, jacob navia wrote:
AJO>>
AJO>> The expression
AJO>> printf("the address is: 0x%x\n",p);
AJO>> where p is some pointer appears in several million lines in
AJO>> existing code.
AJO>
AJO> Has anyone besides Jacob ever seen this construct (or anything
AJO>similar) in real-world code? I've never encountered it. The
AJO>usual idiom in my part of the universe is more like
AJO>
AJO> printf("(%d) %p\n", p!=NULL, (void*)p);
AJO>
AJO>which has the benefit of (a) telling you something useful, and
AJO>(b) being standard, warning-less C code.
AJO>
AJO> Who's been using "%d" or "%x" to print *pointer* values?

%p is a quite new feature for printf(). Neither V7 nor BSD had this, so
the natural way of printing pointers was %x. Don't assume that everybody
out there does a daily update of it's compilers and libraries to the
current gcc.

harti
Nov 14 '05 #24
"jacob navia" <ja***@jacob.re mcomp.fr> writes:
The expression

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

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


Then there are several million errors, and you'd be doing your users a
favor by letting them know.

For example, on an IA-64 system:

#include <stdio.h>
int main(void)
{
char *p = "hello";
printf("Using %%x: p = 0x%x\n", p); /* wrong */
printf("Using %%p: p = %p\n", (void*)p); /* right */
return 0;
}

produces the following output:

Using %x: p = 0x7c0
Using %p: p = 0x4000000000000 7c0

I suspect that platforms with 32-bit ints and 64-bit pointers are
going to become much more common over the next few years. The sooner
programmers realize that all the world's not a VAX^H^H^H x86, the
better. Even if the sizes happen to match, it's still undefined
behavior, and any number of things can go wrong.

If you really want to make sure the address value is displayed in
hexadecimal, and you're willing to assume that pointers and ints are
the same size (e.g., you're writing a quick-and-dirty debugging
statement that will be deleted before the code could ever be ported to
another platform), you can always cast the pointer value to unsigned
int to inhibit the warning. The result may or may not be meaningful,
but at least it avoids undefined behavior.

Or you can just use "%p", which exists for exactly this purpose.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #25
In article <Pi************ *************** *******@unix48. andrew.cmu.edu> ,
aj*@nospam.andr ew.cmu.edu says...

On Tue, 29 Jun 2004, jacob navia wrote:

The expression
printf("the address is: 0x%x\n",p);
where p is some pointer appears in several million lines in
existing code.


Has anyone besides Jacob ever seen this construct (or anything
similar) in real-world code? I've never encountered it.


Unfortunately yes, but not in quite some time. I ran into it
fairly often in the MS-DOS and early Windows days. (Maybe Mr.
Schildt used it a lot in his books???) It was probably in a fair
amount of older legacy UNIX code as well, but I can't recall an
example offhand.

Usually they at least cast the type of p to something appropriate
for the %d or %x on the platform. Every time I encounter something
like that, I fix it, but it doesn't happen much anymore, plus I very
rarely get stuck maintaining code that poor these days.

--
Randy Howard (2reply remove FOOBAR)
"The most amazing achievement of the computer software industry is its
continuing cancellation of the steady and staggering gains made by the
computer hardware industry..." - Henry Petroski

Nov 14 '05 #26
In article <cb**********@n ews-reader3.wanadoo .fr>, ja***@jacob.rem comp.fr
says...
To the contrary of your expectations, I work to make a usable
compiler, not one that will please the purists around c.l.c


Jacob, if you ever (or already) support 64-bit AMD Opteron/AthlonFX or the
Intel clones of same, you're users are going to be in for a rude awakening
when they get to work porting. Yes, it may be so common on 32-bit platforms
for programmers to make assumptions that it *seems* like you're doing them
a favor to ignore it, in the long run, when people WILL be porting a lot
of legacy code to new platforms, it will be a hindrance, not a benefit.

--
Randy Howard (2reply remove FOOBAR)
"The most amazing achievement of the computer software industry is its
continuing cancellation of the steady and staggering gains made by the
computer hardware industry..." - Henry Petroski

Nov 14 '05 #27
In article <cb**********@n ews-reader1.wanadoo .fr>, ja***@jacob.rem comp.fr
says...
"Harti Brandt" <br****@dlr.d e> a écrit dans le message de
news:20******** ***********@bea gle.kn.op.dlr.d e...
On Tue, 29 Jun 2004, jacob navia wrote:
That has nothing to do with purism. Ever cared to work on a machine where
sizeof(void *) > sizeof(int)?
In the next implementation of lcc-win32 that will be the case (64 bit
machine).

In THAT environment I will issue the warning for all pointer/int
conversions.


So people using your 32-bit compiler to develop code which will migrate
to 64 in the future will have to wait until later to be warned of possible
errors in their program. That's not a good idea.
In an environment where sizeof(int)==si zeof(void*) many people
(including me) write printf("pointer value=%#x\n",p) ; to debug
a piece of code.
You write this in new code? Why? I could understand you trying to
support legacy code through some sort of "shut up warnings about this"
mode, but not by default, and certainly don't understand writing new
code with a modern compiler as you describe.
The compiler spitting you hundreds of warnings
would only have the consequence of people IGNORING all warnings.
Strange, I try very hard to get my code to compile (on multiple platforms,
with varying compilers) with no warnings at all, using the highest warning
level on each compiler. It's not always possible, but I try very hard to
do so without bastardizing the source to get there. I have met programmers
that did ignore all warnings, but they were not around long enough in any
case to have a lasting impact.
It is a pity that people here like to have an atmosphere of
aggresivity that is very boring.


I didn't mean to be aggressive earlier, I think it was more *shock* than
animosity. I would have expected this discussion 10 years ago here, not
today, especially in light of the age of the standards that allow it to
be avoided, not to mention the 64-bit transitions currently very active
in a lot of places.

--
Randy Howard (2reply remove FOOBAR)
"The most amazing achievement of the computer software industry is its
continuing cancellation of the steady and staggering gains made by the
computer hardware industry..." - Henry Petroski

Nov 14 '05 #28

"Keith Thompson" <ks***@mib.or g> a écrit dans le message de
news:ln******** ****@nuthaus.mi b.org...
"jacob navia" <ja***@jacob.re mcomp.fr> writes:
The expression

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

where p is some pointer appears in several million lines in
existing code.
Then there are several million errors, and you'd be doing your users a
favor by letting them know.


If they set the debug level to high then yes. If not, the compiler
accepts it. I think this discussion has shown me that
maybe a warning is needed, if the programmer wishes.

lcc-win32 (as its name implies) is a 32 bit system. I am working
in the 64 bit version already, but that is another topic.

For example, on an IA-64 system:

#include <stdio.h>
int main(void)
{
char *p = "hello";
printf("Using %%x: p = 0x%x\n", p); /* wrong */
printf("Using %%p: p = %p\n", (void*)p); /* right */
return 0;
}

produces the following output:

Using %x: p = 0x7c0
Using %p: p = 0x4000000000000 7c0

Yes, this is one of the reasons I think a warning should be
issued if the programmer wishes. It helps porting code
from 32-->64 bits.
I suspect that platforms with 32-bit ints and 64-bit pointers are
going to become much more common over the next few years. The sooner
programmers realize that all the world's not a VAX^H^H^H x86, the
better. Even if the sizes happen to match, it's still undefined
behavior, and any number of things can go wrong.

Yes. I started porting the code and it is hard. Warnings like this
could improve the situation. In any case in the 64 bit system a warning
will be issued since sizeof(int) != sizeof(void *).
If you really want to make sure the address value is displayed in
hexadecimal, and you're willing to assume that pointers and ints are
the same size (e.g., you're writing a quick-and-dirty debugging
statement that will be deleted before the code could ever be ported to
another platform), you can always cast the pointer value to unsigned
int to inhibit the warning.
But this is just effort for throwaway code. Why bother?

Most of those printf statements are for situations where the
debugger is absent.

I started programming when this statements were the only
way of debugging since there wasn't any debugger.

And I wrote (to see if a pointer had a value) %x and was done
with it.

This has worked since a long time. Yes, I know about
%p, but I didn't bother. Why? It continued to work.
The result may or may not be meaningful,
but at least it avoids undefined behavior.

Or you can just use "%p", which exists for exactly this purpose.


Yes, I think I will be forced to write that in the 64 bit system.

I am wary of forcing casts to please the compiler... In a 32
bit system where sizeof void * is the same as sizeof int, this
warning has no sense really, and should be optional.

Do not clutter output. Filter it. Make more verbose
options available but choose a sensible default:

do not clutter...

Nov 14 '05 #29

"Randy Howard" <ra*********@FO OverizonBAR.net > a écrit dans le message de
news:MP******** *************** *@news.verizon. net...
In article <cb**********@n ews-reader3.wanadoo .fr>, ja***@jacob.rem comp.fr
says...
To the contrary of your expectations, I work to make a usable
compiler, not one that will please the purists around c.l.c
Jacob, if you ever (or already) support 64-bit AMD Opteron/AthlonFX or the
Intel clones of same, you're users are going to be in for a rude awakening
when they get to work porting. Yes, it may be so common on 32-bit

platforms for programmers to make assumptions that it *seems* like you're doing them
a favor to ignore it, in the long run, when people WILL be porting a lot
of legacy code to new platforms, it will be a hindrance, not a benefit.


Yes, I added an optional warning. If you want this (and other
warnings) you set higher warning level.

64 bit systems were never a succes, since at least a few
years. Many of them started but never become popular.

And I am sure that issues like %x or %p will be the least
of the problems I will face. Data size bloat, code size bloat...
64 bits is very expensive...

Need more than 4GB of memory recently?

If we bloat things that doesn't make them faster. Twice as
much data needs to be loaded, read-in, etc. This
doesn't make for very significant improvements. But this
is another topic.

Nov 14 '05 #30

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

Similar topics

3
8187
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
4546
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
4426
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
1647
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
2188
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
10402
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
7747
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
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10461
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...
0
10019
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9057
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...
1
7555
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5579
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4122
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
2
3736
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
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.