Can cout alter variables somehow?

Question :

Can cout alter variables somehow?,

Answer :

So I have a function that looks something like this:

float function(){      float x = SomeValue;      return x / SomeOtherValue;  }  

At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this:

float function(){      float x = SomeValue;      cout << x;      return x / SomeOtherValue;  }  

and it worked! Of course, I solved the problem altogether by using a double. But I’m curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I’m missing?

Read More  Could you recommend some guides about Epoll on Linux

(If it’s any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.)

,

Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with.

This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as ‘homing’ the register).

Read More  Generic type conversion FROM string

When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases.

See the MSDN documentation on VC++  You could try compiling with /fp:strict and seeing what happens.

That's the answer Can cout alter variables somehow?, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Read More  any good tool for makefile generation?

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you