Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to use a pointer which point to the address of a variable declared inside "if" statement

Is it ok to use a pointer which point to the address of a variable declared inside "if" statement ? Example as below:

...
int *pTest = 0;
if (...)
{
  int x = 10;
  pTest = &x;
}
else
{
  int x = 100;
  pTest = &x;
}
...
// use pTest 
like image 594
chen ming Avatar asked Jan 25 '26 16:01

chen ming


1 Answers

The problem is the life span of the pointer is greater than that of the object pointed to. This smells bad and you should rethink what you're trying to do.

like image 103
Paul Evans Avatar answered Jan 27 '26 06:01

Paul Evans



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!