473,782 Members | 2,699 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Float to int type casting?

Hi,

1 int main()
2 {
3 float a = 17.5;
4 printf("%d\n", a);
5 printf("%d\n", *(int *)&a);
6 return 0;
7 }

The output is:

0
1099694080

I could not understand why the first printf prints 0 and the other
,1099694080...

I think there is sth different from simple type casting.Is it an
undefined behaviour?
Please let me understand.

Regards.

Feb 5 '06 #1
16 12798
Enekajmer wrote:
Hi,

1 int main()
2 {
3 float a = 17.5;
4 printf("%d\n", a);
Here you're trying to print a float value with a conversion specifier
for int. The results are undefined.
5 printf("%d\n", *(int *)&a);
Here, you're reinterpreting the representation of the float. The results
are implementation defined.
6 return 0;
7 }

The output is:

0
1099694080

I could not understand why the first printf prints 0 and the other
,1099694080...

I think there is sth different from simple type casting.Is it an
undefined behaviour?


[the word is `something']

See above.

HTH,
--ag
--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com
http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"
Feb 5 '06 #2

Artie Gold wrote:
Enekajmer wrote:
Hi,

1 int main()
2 {
3 float a = 17.5;
4 printf("%d\n", a);


Here you're trying to print a float value with a conversion specifier
for int. The results are undefined.
5 printf("%d\n", *(int *)&a);


Here, you're reinterpreting the representation of the float. The results
are implementation defined.
6 return 0;
7 }

The output is:

0
1099694080

I could not understand why the first printf prints 0 and the other
,1099694080...

I think there is sth different from simple type casting.Is it an
undefined behaviour?


[the word is `something']

See above.

HTH,
--ag
--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com
http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"


Thanks i learnt the types of behaviours but i want to learn causes in
more details.To give an example, there is no problem for the snippet
code below:
....
float a=17.5;
int b=a; (type casting from float to int)
printf("b-->%d",b); // as normally, this prints "b-->17"
....

according to this example i guessed the output of the code below as 17
too before i compiled. As contrast its output is 0...

printf("a-->%d",a) //a is in float type
So, what are the causes of this case?The IEEE-754?

Regards.

Feb 5 '06 #3

"Artie Gold" <ar*******@aust in.rr.com> wrote in message
news:44******** ****@individual .net...
Enekajmer wrote:
Hi,

1 int main()
2 {
3 float a = 17.5;
4 printf("%d\n", a);


Here you're trying to print a float value with a conversion specifier
for int. The results are undefined.


Actually, you're trying to print a double value, because the float is
promoted when it's not governed by a formal parameter in a prototype.

If it weren't for that, you'd probably get the same output from both
printfs.

--
RSH
Feb 5 '06 #4
Enekajmer wrote:
Thanks i learnt the types of behaviours but i want to learn causes in
more details.To give an example, there is no problem for the snippet
code below:
...
float a=17.5;
int b=a; (type casting from float to int)
This is, as you rightly say, a cast. It /converts/ a float value in `a`
to it's closest representation as int. Hence, (int)17.5 == 17.
printf("b-->%d",b); // as normally, this prints "b-->17"
...

according to this example i guessed the output of the code below as 17
too before i compiled. As contrast its output is 0...

printf("a-->%d",a) //a is in float type
Artie led you off the track here by saying "conversion specifier". A s a
matter of fact "%d" is a "format specifier". It tells printf()
to /interpret/ whatever is stored in a corresponding parameter (in your
case `a`) as an int. This means that printf() blindly takes whatever is
the bit representation of `a` and interprets these bits as if they were
an `int`. Them actually being an `float` the result is undefined. In
your case, it happened to be 0, but the effect could have been much
worse. Beware the Undefined behaviour monster -- it may make demons
come out of your nose! ;-)
So, what are the causes of this case?The IEEE-754?


No, see paragraph above...

Cheers

Vladimir

--
To invent, you need a good imagination and a pile of junk.
-- Thomas Edison

Feb 5 '06 #5
On 2006-02-05, Enekajmer <en*******@gmai l.com> wrote:
Hi,

1 int main()
2 {
3 float a = 17.5;
4 printf("%d\n", a);
5 printf("%d\n", *(int *)&a);
6 return 0;
7 }

The output is:

0
1099694080

I could not understand why the first printf prints 0 and the other
,1099694080...

I think there is sth different from simple type casting.Is it an
undefined behaviour?
Yes. Both printf lines invoke undefined behavior.
Please let me understand.


hint: a is promoted to a double when passed to printf as a float.
Feb 5 '06 #6
Vladimir S. Oka wrote:
Enekajmer wrote:
Thanks i learnt the types of behaviours but i want to learn causes in
more details.To give an example, there is no problem for the snippet
code below:
...
float a=17.5;
int b=a; (type casting from float to int)

This is, as you rightly say, a cast. It /converts/ a float value in `a`
to it's closest representation as int. Hence, (int)17.5 == 17.

printf("b-->%d",b); // as normally, this prints "b-->17"
...

according to this example i guessed the output of the code below as 17
too before i compiled. As contrast its output is 0...

printf("a-->%d",a) //a is in float type

Artie led you off the track here by saying "conversion specifier". A s a
matter of fact "%d" is a "format specifier". It tells printf()


A slip of the fingers. Thanks for the correction.
--ag to /interpret/ whatever is stored in a corresponding parameter (in your
case `a`) as an int. This means that printf() blindly takes whatever is
the bit representation of `a` and interprets these bits as if they were
an `int`. Them actually being an `float` the result is undefined. In
your case, it happened to be 0, but the effect could have been much
worse. Beware the Undefined behaviour monster -- it may make demons
come out of your nose! ;-)

So, what are the causes of this case?The IEEE-754?

No, see paragraph above...

Cheers

Vladimir

--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com (new post 8/5)
http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"
Feb 5 '06 #7
Robin Haigh wrote:
"Artie Gold" <ar*******@aust in.rr.com> wrote in message
Enekajmer wrote:

1 int main()
2 {
3 float a = 17.5;
4 printf("%d\n", a);


Here you're trying to print a float value with a conversion specifier
for int. The results are undefined.


Actually, you're trying to print a double value, because the float is
promoted when it's not governed by a formal parameter in a prototype.

If it weren't for that, you'd probably get the same output from both
printfs.


It's even worse than that - he is using a variadic function without
a prototype, which makes everything undefined behaviour.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
Feb 5 '06 #8
Vladimir S. Oka wrote:
Enekajmer wrote:
Thanks i learnt the types of behaviours but i want to learn causes in
more details.To give an example, there is no problem for the snippet
code below:
...
float a=17.5;
int b=a; (type casting from float to int)


This is, as you rightly say, a cast. It /converts/ a float value in `a`
to it's closest representation as int. Hence, (int)17.5 == 17.


No, it's not a cast. It is, on the other hand, a conversion.
printf("b-->%d",b); // as normally, this prints "b-->17"
...

according to this example i guessed the output of the code below as 17
too before i compiled. As contrast its output is 0...

printf("a-->%d",a) //a is in float type


Artie led you off the track here by saying "conversion specifier". A s a
matter of fact "%d" is a "format specifier". It tells printf()
to /interpret/ whatever is stored in a corresponding parameter (in your
case `a`) as an int. This means that printf() blindly takes whatever is
the bit representation of `a` and interprets these bits as if they were
an `int`. Them actually being an `float` the result is undefined. In
your case, it happened to be 0, but the effect could have been much
worse. Beware the Undefined behaviour monster -- it may make demons
come out of your nose! ;-)


Actually, it does not take the bit pattern and reinterpret it. It
assumes that the parameter is an int and tries to read that and this is
undefined behaviour (i.e. anything can happen) because the standard says
it is.

There are calling conventions where even varargs parameters are passed
in appropriate registers, so in this case it could read whatever the
first integer register happens to contain which could have absolutely
nothing to do with the contents of a. The specific implementation I'm
thinking of (a real one) can actually cause even more fun. If the
parameter is a double it gets passed in a floating point register, but
also converted to an int and passed in an integer register, so you would
actually get the result the OP expected. However, when you pass an int
that is *only* passed in an integer register, so if you try to print an
int using the format specifier for a double, it will try to print
whatever happened to be in the floating point register.

The implementation happens to be the latest version of Visual Studio
when given appropriate options.

The moral of this is *never* try to say what C implementations do when
you invoke undefined behaviour, for it's ways are stranger than your
imagination can conceive.

It is reasonable to wonder why something is undefined, and sometimes
useful to know how undefined behaviour can manifest, but only if you
accept that literally *anything* can cause a different behaviour,
including it deciding to show a picture of your boss in the nude.
So, what are the causes of this case?The IEEE-754?


No, see paragraph above...


Indeed.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Feb 5 '06 #9
On Sun, 05 Feb 2006 11:16:49 -0600, Artie Gold
<ar*******@aust in.rr.com> wrote in comp.lang.c:
Enekajmer wrote:
Hi,

1 int main()
2 {
3 float a = 17.5;
4 printf("%d\n", a);


Here you're trying to print a float value with a conversion specifier
for int. The results are undefined.
5 printf("%d\n", *(int *)&a);


Here, you're reinterpreting the representation of the float. The results
are implementation defined.


[snip]

No, undefined. There are only two defined ways to look at the bits of
an object of type float, those are using an lvalue of type float, or
using an array of unsigned characters the size of a float.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Feb 5 '06 #10

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

Similar topics

1
4076
by: maxim vexler | last post by:
in a book i am ready now : O'Reilly - Web Database Application with PHP and MySQL, 2nd ed. by David Lane, Hugh E. Williams on chapter 9 the author give an example for age validation : (simplified code, not a direct quote) $dob = mktime(0,0,0, 5, 3, 1983); if ((float)$dob > (float)strtotime("-18years")) {
3
5837
by: Cgacc20 | last post by:
I have a c struct from old code that cannot be modified and I am trying to write a wrapper C++ class around it. This class is often passed as a pointer to some c functions of a library and I wanted to keep my new class transparent and compatible with those functions. That is, when using the code, I should be able to do either: oldVector xyz; function( &xyz ); myVector xyz; function( &xyz );
5
8269
by: Suzanne Vogel | last post by:
** Isn't the 'static_cast' operator the same as traditional type casting? ie, Aren't the following ways of getting b1, b2 the same? // 'Derived' is derived from 'Base' Derived* d = new Derived(); Base* b1 = static_cast<Base*>(d); Base* b2 = (Base*)d; // traditional type casting Such is my understanding from code samples, my own uses, and this: http://www.cplusplus.com/doc/tutorial/tut5-4.html
1
9139
by: JohnK | last post by:
under the covers is type casting in VB.Net the same as C# ? myObject = CType(..,..) in VB.Net vs myObject = (SomeClass)aObject
1
3436
by: chook | last post by:
Wherein differences between type casting in C++ : static_cast, dinamic_cast, reinterpret_cast, const_cast and C type casting, like xxx = (type)yyy; What, when and why is necessary to use?
9
4051
by: Roman Mashak | last post by:
Hello, All! Given the sample piece of code I have: #include <stdio.h> #include <string.h> int main(void) { short int i, j;
23
3531
by: René Nordby | last post by:
Hi there, Is there anyone that knows how to do the following? I have a class A and a class B, that 100% inherits from class A (this means that I don't have other code in class B, than the Inherit statement).
7
4223
by: Ben R. | last post by:
How does automatic type casting happen in vb.net? I notice that databinder.eval "uses reflectoin" to find out the type it's dealing with. Does vb.net do the same thing behind the scenes when an invisible cast is made? Is there any reason why one would use databinder.eval while in VB.NET? I can see why one might use it in C# so as to avoid specifying the type for the cast but since this is not necessary in VB.NET, I'm not sure I follow. ...
11
32476
by: Frederic Rentsch | last post by:
Hi all, If I derive a class from another one because I need a few extra features, is there a way to promote the base class to the derived one without having to make copies of all attributes? class Derived (Base): def __init__ (self, base_object): # ( copy all attributes ) ...
0
9474
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,...
1
10076
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
9939
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
8964
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
7486
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
6729
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
5375
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
5507
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3633
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.