views:

76

answers:

2

This is more of a theory question, then any actual code. I understand that if you declare a variable int i; then it sets aside 4 bytes in memory for the integer i. I understand if you use malloc to create your memory as well.

I am curious how memory is handled when you do something like

int x;
int y;
double z;

z = (float)x/(float)y;

When you cast like this, how is the memory handled. Does the program create floats and store x and y and then do the division? Or is it something outside of memory?

Thanks for any explanation!

+1  A: 

Yes, the straightforward way is to create temporary variables - usually on stack. In some cases the compiler can be able to optimize the unnecessary temporary variables creation away. If you really care you should look into the produced disassembly.

sharptooth
Hmm, this would imply if you had int x; and float(x), you'd have memory taken up for the int x, and then memory taken up for float. I wonder if its more memory efficient to just declare x as a float. I suppose not because the later cast is only around for the calculation, correct?
Blackbinary
@Blackbinary: It may or it may not, you don't know until you try. You try both, look at the assembly and make a conclusion. It might allocate space for a million `int`'s just because it feels like it, we don't know.
GMan
@Blackbinary: If you're using it as a float, declare it as a float. The cast is also likely to cost a very small amount of execution time, for what that's worth (almost nothing).
David Thornley
A: 

It's of course completely implementation dependent, and platform-specific. By the way, sizeof(int) isn't necessarily 4 like you say.

For your code, one possible output might be (off the top of my head):

fild [x] // load x from the stack into a register
fidiv [y] // divide by y loaded from the stack
fstp [z] // store the result in z

This would be on a processor with an FPU.

GMan
Thats way over my head, but thanks.
Blackbinary