473,805 Members | 1,905 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 3430
"Arthur J. O'Dwyer" wrote:
[...]
printf("the address is: 0x%x\n",p);
[...] printf("(%d) %p\n", p!=NULL, (void*)p); [...] Who's been using "%d" or "%x" to print *pointer* values?


I have old legacy code, from before "%p" existed, with a similar construct.
However, it uses "%lx" and the cast "(long)ptr" . This at least "works" on
systems where pointers are not bigger than longs. (Which is all platforms
for which it is currently ported to.)

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody at spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+

Nov 14 '05 #31
"jacob navia" <ja***@jacob.re mcomp.fr> wrote:
"Dan Pop" wrote:
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);


No it isn't. Putting anything other than an int, or a type that promotes
to int, is undefined. (Having said that, you can of course make
your compiler define that behaviour. But this code is not portable
to other compilers).
specially in debugging code.
I always write standard code for debugging. Why take the risk
of having your debugging information come out wrong because you
did something undefined? When you're frustrated with some hard-to-find
bug, the last thing you need is the debugging to not work.
Granted, this is weird, but how to discriminate between
legal and wrong usage?
Legal usage adheres to the standard, wrong usage doesn't.
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.
Do you not know about %p ?
But this is at the limit of what a compiler can do.


This is all very much simpler than, say, writing a C++ compiler.
I'm sure you could even build a runtime check to match the
format string to the types of the arguments.
Nov 14 '05 #32
Harti Brandt wrote:
%p is a quite new feature for printf().
You must have an interesting definition of "quite new" in that it
appeared in the 1989 standard and K&R 2.
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.


One needn't have a daily update, just one from, oh, the last 10 years or
so.


Brian Rodenborn
Nov 14 '05 #33

"Default User" <fi********@boe ing.com.invalid > a écrit dans le message de
news:40******** *******@boeing. com.invalid...
Harti Brandt wrote:
%p is a quite new feature for printf().


You must have an interesting definition of "quite new" in that it
appeared in the 1989 standard and K&R 2.
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.


One needn't have a daily update, just one from, oh, the last 10 years or
so.


As I mentioned in another thread, I started learning C using those printf
statements for debugging since there wasn't any debugger in those times.

And the usage became an habit. It has been working since
more or less 20 years.

Is that a terrible sin?

Do not know. I am not a star programmer, neither the one
that never makes mistakes sorry.

Those printf statements never survived a lot anyway. Why
should I bother?

Is this extremely important?

Maybe. The fact that I check printf (as few compilers do
actually) is ignored, and an oversight is amplified.


Nov 14 '05 #34
In article <cb**********@n ews-reader2.wanadoo .fr>, ja***@jacob.rem comp.fr
says...
Yes, I added an optional warning. If you want this (and other
warnings) you set higher warning level.
If your compiler supports the logical equivalent of gcc's -pedantic
it should be there by default. Perhaps also for whatever might
equate to -std=c89 or -std=c99.
64 bit systems were never a succes, since at least a few
years. Many of them started but never become popular.
I guess all of those new macintoshes I see people buying are a
failure. Apparently the very high volume of 64-bit AMD servers,
desktops and even notebooks now being sold are also a failure.
If you said "Itanium" I would be in agreement. In the first
year of general availability, x86_64 processors outsold Itanium
about 8:1, despite being to market 4 or 5 years later. 64-bit
is coming, and quickly, particularly on the server side, but also
the gamer kids are jumping on the bandwagon.

I have a 64-bit AMD notebook now, and it's wonderful, even when
running 32-bit windoze, but far more fun with SuSE 9.1 64-bit.
And I am sure that issues like %x or %p will be the least
of the problems I will face.
True. A lot of programmers, especially maintaining large WIN32
apps are having a hell of a time moving, because of all of the
MS data type proliferations that make really painful assumptions
about the sizes of things. If however you stick to the "portable
C sandbox", it's very, very painless. YMMV.
Data size bloat
Not necessarily, unsigned char's are still available. :-) So
are most of the other "smaller" data types. Fortunately, limits.h
has been around for a while, which helps considerably in this area.
code size bloat...
Minor in the grand scheme of things, but yes...
64 bits is very expensive...
Actually, 64-bit Opteron servers typically sell for about 1/2 of
a slower, less capable Xeon server. :-) (I know what you meant)
Need more than 4GB of memory recently?
Actually, yes. Not so much for myself, but because I needed to
write some code to stress memory above 4GB on IA-32 systems
that supported it via PAE. Not pretty. On 64-bit platforms,
it's unlikely I'll be around long enough to see a machine with
enough memory sticks to fill up the address space.

More typically, database programmers have been fighting this
problem for quite a while. If you really want to see an ugly
hack to get around this problem, go search for "AWE" and memory
on the MSDN website. Not pretty, but in a sense unavoidable
to get around 4GB on a 32-bit box.

More concretely, it's a daily issue for server development and
end users, where 4GB limitations on file sizes really suck when
you have a 2TB filesystem at your disposal, thanks to 32-bit
file offset issues. There are hacks to get around the problem of
course. The point is, it's not just about how much memory you have
installed.
If we bloat things that doesn't make them faster.
Taken at face value, that's true. It doesn't mean that a 64-bit
platform and software is automatically bloated without any
redeeming benefits. A fair amount of crypto code for example
can be shown to be much, much more efficient on 64-bit platforms,
but it's also true for quite a few other things. There are also
some major architectural benefits with the AMD 64-bit technology
such as Hypertransport, which flat out slay Intel FSB memory
designs on throughput, particularly in SMP implementation, which is
a big improvement as processor speed increases continue to outpace
memory performance in general.
Twice as much data needs to be loaded, read-in, etc.
And 64-bit designs are much better at loading in twice as much
data than 32-bit designs, pretty much across the board.

You might consider that people said almost the same thing (and
were proved wrong fairly quickly) when the 8 -> 16-bit transitions
and the 16 -> 32-bit transitions happened. No sense fighting
progress.
This doesn't make for very significant improvements.


Actually, it does, but it sounds as if you haven't had much experience
working on various 64-bit platforms yet, so it doesn't make much
sense to continue this until some later date when you have.

The main point still is that a compiler should support portability of code
compiled with it, not believe, wish, or otherwise pretend that it won't
happen.

--
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 #35

"Randy Howard" <ra*********@FO OverizonBAR.net > a écrit dans le message de
news:MP******** *************** *@news.verizon. net...
In article <cb**********@n ews-reader2.wanadoo .fr>, ja***@jacob.rem comp.fr
says...
but it sounds as if you haven't had much experience
working on various 64-bit platforms yet, so it doesn't make much
sense to continue this until some later date when you have.


I ported lcc-win32 to windows XP 64 bits.

Rewrote the assembler, the linker, adapted the debugger.

It is working, in an embryonic stage yet.

sizeof(void *) == 64, sizeof(int) == 32.

The best thing is not the 64 bit but *the EXTRA REGISTERS!!!*

8 new registers at last... The Intel architecture didn't saw that
for 20 years...

I think lcc-win32 will eventually migrate to

sizeof(void *) == 32, sizeof(int) 32
sizeof( __long void *) == 64, sizeof (long long) == 64.

For the few data items where you may need more than
4GB of addressing space a special pointer type would be more efficient
than putting all pointers in 64 bit carrying mostly
32 bits of zeroes around.

There is no free lunch. The complexity of having
two pointer types can become an obstacle.

I haven't decided yet which way to go.

Nov 14 '05 #36
In article <cb**********@n ews-reader5.wanadoo .fr>,
"jacob navia" <ja***@jacob.re mcomp.fr> wrote:
I think lcc-win32 will eventually migrate to

sizeof(void *) == 32, sizeof(int) 32
sizeof( __long void *) == 64, sizeof (long long) == 64.


Are you sure about that?
Nov 14 '05 #37

"Christian Bau" <ch***********@ cbau.freeserve. co.uk> a écrit dans le message
de news:ch******** *************** **********@slb-newsm1.svr.pol. co.uk...
In article <cb**********@n ews-reader5.wanadoo .fr>,
"jacob navia" <ja***@jacob.re mcomp.fr> wrote:
I think lcc-win32 will eventually migrate to

sizeof(void *) == 32, sizeof(int) 32
sizeof( __long void *) == 64, sizeof (long long) == 64.


Are you sure about that?


The rationale is that most programs do have a certain use of the
extra registers provided by the new architecture, but will never
need more than 4GB address range for most pointers.

Since 32 bit isntructions are smaller and the size of the
pointers in structures doesn't change, it becomes an
easy way to migrate the existing software base to 64 bits
without a lot of pain.

Nothing changes, you just have a new "long"
pointer type when you need it.

In the moment where the complexity of two pointers
types outweights the performance benefits this is
moot.

But I do not have implemented that yet. It is
a lot of work, much more than just following the
trend and using 64 bit pointers.


Nov 14 '05 #38
"jacob navia" <ja***@jacob.re mcomp.fr> writes:
[...]
lcc-win32 has several levels of warnings. After this discussion I have added
a warning when the warning level is higher than normal for all
implicit pointer/int conversions in the printf formats.


It's not really an implicit conversion. At best, it's a pointer
representation being interpreted as if it were an integer. The effect
is often identical, but it's best not to think of it as a "conversion ".

Consider an analagous call:
printf("f = %d\n", f);
where f is of type float. There is no conversion from float to int,
just a float representation being interpreted as an int value. The
displayed value will most likely be garbage.

It happens that conversions between floats and integers typically have
to do an actual conversion to get the right value, while conversions
between pointers and integers typically just copy the bits. That's
why
printf("f = %d\n", some_float_valu e);
typically prints garbage, while
printf("p = 0x%x\n", some_pointer_va lue);
often gives you something that looks meaningful, but both are equally
undefined behavior, and both will fail badly on some real-world
systems.

I urge you to issue a warning for both cases at the default warning
level; if you want to provide some mechanism to inhibit certain
warnings, that's fine. (This is my opinion; the standard, of course,
doesn't require a warning in either case.) I also urge you to use "%p"
in your own code.

--
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 #39
jacob navia wrote:

"Default User" <fi********@boe ing.com.invalid > a écrit dans le message de
news:40******** *******@boeing. com.invalid...
Harti Brandt wrote:
%p is a quite new feature for printf().


You must have an interesting definition of "quite new" in that it
appeared in the 1989 standard and K&R 2. One needn't have a daily update, just one from, oh, the last 10 years or
so.


As I mentioned in another thread, I started learning C using those printf
statements for debugging since there wasn't any debugger in those times.

And the usage became an habit. It has been working since
more or less 20 years.

Is that a terrible sin?


As my reply was not to you, but to someone who maintained that %p was
some new invention, I don't know why you are whining to me. I don't give
a good goddamn why you choose not to use what the language provides.

Brian Rodenborn
Nov 14 '05 #40

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

Similar topics

3
8190
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
4550
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
4182
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
4434
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
1649
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
2193
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
10406
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
7748
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
4487
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
10609
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
10360
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10366
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
9185
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
5542
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
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4323
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
3845
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3007
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.