c++ - can anyone please explain me why the two "results" are different? -
this question has reply here:
can local variable's memory accessed outside scope? 18 answersi have code:
#include <iostream> using namespace std; int & squareref(int ); int main() { int number1 = 8; cout << "in main() &number1: " << &number1 << endl; int & result = squareref(number1); // cout << "in main() &result: " << &result << endl; cout << result << endl; cout << result << endl; cout << number1 << endl; } int & squareref(int rnumber) { cout << "in squareref(): " << &rnumber << endl; rnumber *= rnumber; homecoming rnumber; }
the programme produces next output:
in main() &number1: 0x28ff08 in squareref(): 0x28fef0 64 1875681984 8
can please explain why 2 "results" different , suppose same isn't ?
you invoking undefined behaviour returning reference local variable:
test.cc:19:7: error: reference local variable ‘rnumber’ returned [-werror=return-local-addr] int & squareref(int rnumber) {
rnumber copied on stack call. after call, value on stack undefined, , might alter due subsequent calls. reference homecoming points location on stack , not hold actual value.
in general, when these things happen, helpful turn on warnings compiler can give you. gcc, flags -wall -wextra -werror
provide lot of helpful warnings, such these. in general, code should compile without throwing any warnings (except maybe unused variables/parameters in function stubs, although there macros explicitly skip on these).
c++ reference return
No comments:
Post a Comment