Maybe a weird question... but anyways.

Started by
3 comments, last by kenwi 22 years, 2 months ago
okay... this maybe be a bit stupid question but it cant help. Me and a friend had a little discussion about wheter it''s the same if I write: float thisfloat; thisfloat = 0.005; or if I write "float thisfloat = 0.005;" Would those 2 code examples be compiled into the same and not have any relevance if I do it this or the other way? My personal thought would be: float thisfloat = 0.005; would be the fastest one, because.. well after my experience. If I write float thisfloat; it sets a value for thisfloat (ie: -0.7123798) and afterwards I set another value to the float(0.005).. This is 2 "operations"(??) compared to the other way which has only 1(?)... Please correct me if I''m wrong and enlighten me if it''s any difference to the ways.. Thanks in advance Kenneth Wilhelmsen Try my little 3D Engine project, and mail me the FPS. WEngine
Or just visit my site -------------------------- He who joyfully marches to music in rank and file has already earned my contempt. He has been given a large brain by mistake, since for him the spinal cord would fully suffice. This disgrace to civilization should be done away with at once. Heroism at command, senseless brutality, deplorable love-of-country stance, how violently I hate all this, how despicable and ignoble war is; I would rather be torn to shreds than be a part of so base an action! It is my conviction that killing under the cloak of war is nothing but an act of murder
Advertisement
Look at this code:

  float x;cout << x << endl;  


You''ll get a strange number printed to the console screen. YOu may think that the number is assigned to the variable x. It isn''t though. That number is just whatever happened to be in memory at the location where that particular variable was created.

There is an exception though. AFAIK, when compiling in Debug mode in MSVC++, a specific value is assigned to variables when they are declared regardless of whether or not they are initialized. In Release mode, however, this is not done, and the two code samples should be identical.

The only way to know for sure, however, is to look at the assembly output.
Both ways are equal.

If you write "float thisfloat;", the variable doesn''t get set to a random value on creation, instead certain memory location from stack is reserved for it and whatever happens to be in that location becomes the value of thisfloat initially.

So each way requires memory allocation from stack (which is calculated already at compile time), and the only operation that counts is the assignment.
TerranFury:

Hmm, my MSVC++ (6.0) doesn''t seem to do this initialization even in debug mode..
>my MSVC++ (6.0) doesn''t seem to do this initialization even in debug mode..

I believe it only initialises arrays and pointers.

This topic is closed to new replies.

Advertisement