Fedor
Fedor

Reputation: 21317

Wrong computation of sum in a constant expression

My program after porting to Visual Studio shows some weird results. After reduction I came to this minimal reproducible example:

consteval auto operator +( auto x, auto&& y ) {
    return x += y;
}

struct S {
    constexpr operator float() { return 1; }
};

int main() {
    return 0 + S{};
}

I expected it to return 1, but in Visual Studio it returns just an arbitrary number 3422303056, and the assembly code suggests that this value is computed during constant evaluation:

main    PROC
        mov     eax, 1610363728                     ; 5ffc3350H
        ret     0
main    ENDP

Online demo: https://gcc.godbolt.org/z/j7eY4qM1s

is the program somehow illformed?

Upvotes: 7

Views: 169

Answers (1)

user17732522
user17732522

Reputation: 76829

There are no surprising C++ rules that would be relevant here.

Overload resolution and constant expression evaluation should behave here as naively expected and the program should return 1.

Seems to be a MSVC bug.

(Technically I suppose float is not required to be able to represent 1 exactly per C++ standard. In that case the result may be different. But that is not the case here where a IEEE 754 floating point implementation is used.)

Upvotes: 3

Related Questions