mmirzadeh
mmirzadeh

Reputation: 7079

Is returning the address of temporary an undefined behavior here?

Is this undefined behavior in c++?

#include <iostream>

const double& abs(const double& x){
    return x>0 ? x:-x;
}

int main () {

    double x = -10.0;
    double y = abs(x);

    std::cout << y << std::endl;

    return 0;
}   

g++ does not like it:

mem.cpp: In function ‘const double& abs(const double&)’:
mem.cpp:4: warning: returning reference to temporary

and valgrind generates all sort of errors.

Upvotes: 2

Views: 87

Answers (1)

James Kanze
James Kanze

Reputation: 153919

Yes. The results of the ternary operator are a temporary, and will cease to exist once you return from the function.

Upvotes: 1

Related Questions