Can cout alter variables somehow?

前端 未结 2 1207
被撕碎了的回忆
被撕碎了的回忆 2021-02-08 16:32

So I have a function that looks something like this:

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

At some point,

2条回答
  •  太阳男子
    2021-02-08 17:12

    Printing a value to cout should not change the value of the paramter in any way at all.

    However, I have seen similar behaviour, adding debugging statements causes a change in the value. In those cases, and probably this one as well my guess was that the additional statements were causing the compiler's optimizer to behave differently, so generate different code for your function.

    Adding the cout statement means that the vaue of x is used directly. Without it the optimizer could remove the variable, so changing the order of the calculation and therefore changing the answer.

提交回复
热议问题