coin cheung
coin cheung

Reputation: 1095

Why my program return different results at optimization level of O0 and O2

Here is my code:

#include<iostream>

const int & Min(const int& a, const int& b);


int main() {
    using namespace std;

    auto&& val = Min(1,2);

    cout << val << endl;
    return 0;
}


const int & Min(const int& a, const int& b) {
    return a < b ? a : b;
}

If I compile this with O0 option, g++ -O0 main.cpp -o main, the result is 1. If I compile with O2 option, g++ -O2 main.cpp -o main, this will give a result of 0.

Why this give different results ?

Upvotes: 0

Views: 478

Answers (1)

songyuanyao
songyuanyao

Reputation: 172864

Your code has undefined behavior.

For Min(1,2);, two temporary objects initialized from 1 and 2 are constructed and then bound to the reference parameter a and b. Note that the temporary objects are destroyed immediately (after the full expression). Min() returns either a or b by reference; that means the returned reference is always dangled, dereference on it leads to UB, i.e. anything is possible.

EDIT

Literals (like 1 and 2) can't be bound to reference directly, temporary is needed instead,

Temporary objects are created when a prvalue is materialized so that it can be used as a glvalue, which occurs (since C++17) in the following situations:

  • binding a reference to a prvalue

Upvotes: 14

Related Questions