0

I'm trying to understand how references/pointers/dereferencing works in c++. Please see below for some example code :

#include <iostream>
#include <cstdio>

int& plusThree(int num)
{
    int threeMore = num + 3;
    //std::cout << "threeMore is " << threeMore << "\n";
    //printf("threeMore is %d", threeMore);
    return threeMore;
}


int main()
{
    int three = plusThree(0);
    std::cout << "three is " << three << "\n";
    return 0;
}

The function plusThree() shouldn't work, and if you run the code, it doesn't. It'll return three is 0. However, if you uncomment either of the lines which prints threeMore, main will now print three is 3...

So my questions are as follows:

  1. Why does the function plusThree() not work? is it because int& means it should return an integer reference, but return threeMore is returning an int?

  2. Why does the function plusThree() now work, if one of std::cout or printf is uncommented?

Thanks!

1 Answers1

0

As @Retired Ninja mentioned, returning a reference to a local variable from a function has undefined behavior...

The int threeMore; should be defined outside the function, or it must be returned by value not a reference.

You must change plusThree's implementation, or the int threeMore; variable:

int threeMore;

Return by reference:

int threeMore = 0;

int& plusThree(int num)
{
    threeMore = num + 3;
    //std::cout << "threeMore is " << threeMore << "\n";
    //printf("threeMore is %d", threeMore);
    return threeMore;
}

Return by value:

int plusThree(int num)
{
    int threeMore = num + 3;
    //std::cout << "threeMore is " << threeMore << "\n";
    //printf("threeMore is %d", threeMore);
    return threeMore;
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055