0

Is it "good practice" to create a variable inside a function and giving a reference back?

Here is a minimal example:

#include <iostream>

int* add(int* a, int* b)
{
  int c = *a + *b; // c is created here and a reference is given back
  int* p_c;
  p_c = &c;
}

main()
{
  int a = 1;
  int b = 2;

  int* p_c = add(&a, &b);

  std::cout << *p_c << std::endl;
}

In the main function *p_c gives me the correct value. However, the value is created in the fuction add. Is this causing problems?

  • 6
    `Is it "good practice" to create a variable inside a function and giving a reference back?` - **NO** – user1810087 Feb 26 '20 at 09:59
  • 1
    You should always compile with warnings enabled `-Wall -Wextra -Werror`, they will tell you what is wrong with your code. – Maxim Egorushkin Feb 26 '20 at 09:59
  • 1
    It's not just not a good practice, it will cause undefined behavior. Usually pretty quickly too. – Omer Tuchfeld Feb 26 '20 at 10:00
  • 3
    I don't see any return value. UB in 2 cases in a single function :-) – Klaus Feb 26 '20 at 10:00
  • @Scheff That's not fatal. Not returning a value is. – Maxim Egorushkin Feb 26 '20 at 10:00
  • Those aren't even references. They're pointers. And your function that is supposed to return a `int*` isn't returning anything. – Blaze Feb 26 '20 at 10:00
  • @MaximEgorushkin Oops. Overlooked. – Scheff's Cat Feb 26 '20 at 10:02
  • It is natural to wonder about such a thing. Nearly every C or C++ programmer has made this error at least once. The question is not a bad one in of itself. The minimal example has errors is probably the primary detractor besides it being a fairly common duplicate. – jxh Feb 26 '20 at 10:06
  • All functions in C++ must have a declared return type (may be `void`) and the one of `main` must be `int`. Yours is missing one. Add to the compiler flags mentioned above for warnings also the flag `-pedantic-errors` which will tell your more clearly if you don't follow standard C++ rules. – walnut Feb 26 '20 at 10:07
  • your code looks like you think using more pointers would make code better. That isnt the case. If possible references are to be preferred, but you do not even need a reference to add two numbers in a function and return the result. – 463035818_is_not_an_ai Feb 26 '20 at 10:44

0 Answers0