Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the issue with this static variable assignment to a pointer in local function?

Tags:

c++

c

static

int* func(int *ptr)
{
  static int a = 5;
  ptr = &a;
  return ptr;
}

Someone asked me this question in an interview. Now the point is, the variable 'a' is static, so, unlike ordinary variables which are declared, which loses it's value (popped from stack) once the function returns, this variable retains it's value as it is a static one.

Then i didn't understand, what's the issue with this piece of code?

like image 247
RajSanpui Avatar asked Nov 30 '25 19:11

RajSanpui


1 Answers

There is no point in having ptr as a parameter. The passed value is not used. You could change this to

int* func()
{
  static int a = 5;
  return &a;
}
like image 168
Henrik Avatar answered Dec 03 '25 08:12

Henrik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!