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;
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
Обратная Связь
Зарегистрируйся сейчас
или Подпишись на будущие тесты