Casting problem ?!

S

Stranger

what is stored in "i" variable in this program ?

long i;
float y;
float number;
y = number;
i = * ( long * ) &y;

notice that "number" variable has been initialized ...
 
C

Carlos Martinez Garcia

The first N bytes of y.
N=sizeof(long)

The content of the first N bytes depends on how your computer an OS
represents floats in memory.
 
N

Neelesh Bodas

Stranger said:
what is stored in "i" variable in this program ?

long i;
float y;
float number;
y = number;
i = * ( long * ) &y;

notice that "number" variable has been initialized ...

Where is the initialization of "number"? I nothing initialized, and y
assigned a junk value.
Also, please use C++-style casts - they are provided for a reason.
The result would be a junk value in "i".
 
M

Mark

i *think* he may have meant "note" that "number" has been initialized.
ie, elsewhere in his program that he has not shown.

however, i wouldnt know whats in i... why cant you just do
i = long(y)? or (long)y?
 
M

mlimber

Mark said:
i *think* he may have meant "note" that "number" has been initialized.
ie, elsewhere in his program that he has not shown.

however, i wouldnt know whats in i... why cant you just do
i = long(y)? or (long)y?

Perhaps because that was not the author's intent. If s/he wanted to
truncate y to the nearest whole number, s/he would have done just what
you said. If, however, s/he wanted an implementation-dependent,
bit-wise representation of y, then the nasty pointer casts may
accomplish that (depending on the sizes of the various data types).
Using reinterpret_cast would be preferred because it would signal
non-portable code.

Cheers! --M
 
D

deane_gavin

mlimber said:
Perhaps because that was not the author's intent. If s/he wanted to
truncate y to the nearest whole number, s/he would have done just what
you said. If, however, s/he wanted an implementation-dependent,
bit-wise representation of y, then the nasty pointer casts may
accomplish that (depending on the sizes of the various data types).
Using reinterpret_cast would be preferred because it would signal
non-portable code.

Isn't the OP's code

float y;
float number;
y = number;

undefined behaviour is number is not initialised before being assigned
to y?

Gavin Deane
 
R

Ron Natalie

Carlos said:
The first N bytes of y.
N=sizeof(long)

The content of the first N bytes depends on how your computer an OS
represents floats in memory.

It might not be even that. There's no guarantee that float* can
be converted to long* with a cast.
 

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

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top