Thread overview
Checking pointers
Jun 01, 2005
Trevor Parscal
Jun 01, 2005
Sean Kelly
Jun 01, 2005
zwang
Jun 01, 2005
pragma
June 01, 2005
How should i go about checking to see if a pointer is set?

I can set a pointer to null, and also to point to something. So how do I check if it is null or not?

int* foo = null;
int bar = 5;
foo = &bar;

if(foo == null)
{
	// don't use it
}
else
{
	// use it
}

I have tried several things, nothing works so far..

-- 
Thanks,
Trevor Parscal
www.trevorparscal.com
trevorparscal@hotmail.com
June 01, 2005
In article <d7kfom$1p4q$1@digitaldaemon.com>, Trevor Parscal says...
>
>How should i go about checking to see if a pointer is set?
>
>I can set a pointer to null, and also to point to something. So how do I check if it is null or not?
>
>int* foo = null;
>int bar = 5;
>foo = &bar;
>
>if(foo == null)
>{
>	// don't use it
>}

if(foo == null) works just fine, though it could cause problems with template
code (since comparing a class reference to null can cause an access violation).
The alternate that always works is if(foo).


Sean


June 01, 2005
Trevor Parscal wrote:
> How should i go about checking to see if a pointer is set?
> 
> I can set a pointer to null, and also to point to something. So how do I check if it is null or not?
> 
> int* foo = null;
> int bar = 5;
> foo = &bar;
> 
> if(foo == null)
> {
>     // don't use it
> }
> else
> {
>     // use it
> }
> 
> I have tried several things, nothing works so far..
> 

You've answered your own question.
Either "foo is null" or "foo === null" would do.
"foo == null" is also okay for pointers of primitive types.
June 01, 2005
In article <d7kfom$1p4q$1@digitaldaemon.com>, Trevor Parscal says...
>
>How should i go about checking to see if a pointer is set?
>
>I can set a pointer to null, and also to point to something. So how do I check if it is null or not?
>
>int* foo = null;
>int bar = 5;
>foo = &bar;
>
>if(foo == null)
>{
>	// don't use it
>}
>else
>{
>	// use it
>}
>
>I have tried several things, nothing works so far..

Have you tried the 'is' operator?

if(foo is null){ /* blah */ }

- EricAnderton at yahoo