Is this a c++ compilation bug of the Visual Studio 2019? (Function parameter is passed incorrectly when optimization is turned ON)

Viewed 226

vs2019 Version 16.11.1

Function parameter is passed incorrectly when optimization is turned ON

Below is a minimal example code I’ve built to reproduce the problem:

  1. The initial value of the member variable ‘x’ of ‘foo’ is 32.0f
  2. Use the local variable ‘old’ in ‘inner_func’ to cache the ‘x’ value and pass it to the function ‘inner_print’ to print
  3. It should output 32, but the actual output is 10 under release build (debug build is ok, and doesn’t have this issue)
#include <iostream>

using namespace std;

class foo {
public:
    foo() {
        x = 32.0f;
        min_x = 4.0f;
    }

    void func(float val) {
        if (val < get_min_value()) {
            val = get_min_value();
        }

        inner_func(val);
    }

protected:
    void inner_func(float val) {
        float old = x;
        x = val;
        inner_print((int)old);
    }

    virtual float get_min_value() {
        return min_x;
    }

    void inner_print(int val) {
        cout << val << endl;
    }

private:
    float x;
    float min_x;
};

int main() {
    foo f;
    f.func(10.0f);

    return 0;
}

As @engf-010 suggested, I had reported this to Microsoft (use the feedback button in the right-upper corner of VS) using the redused-down version by @Bill Lynch: C++ compiler bug: incorrect output produced when optimization is turned ON (for vs2017, vs2019, vs2022)

And there is a report of a similar issue in the VS Developer Community: C++ compiler: Function parameter is passed incorrectly when optimization is turned ON

0 Answers
Related