What will be printed to stdout when executing this code?

#include <iostream>
using std::cout;

int* treble(int);

int main(void)
{
  int num = 5;
  int* ptr = 0;
  ptr = treble(num);
  cout << *ptr;
  return 0;
}

int* treble(int data)
{
  int a = 0;
  if (data >= 5) {
    int b = 3 * data;
    return &b;
  }
  return &a;
}
Explanation
The address of the variable located on the stack will be returned from the function. By the moment the treble() function is quit, this variable will be destroyed, so when you try to access this variable on the line cout << *ptr it will be undefined behavior.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести