Finding if a pointer is null

Hi all,
I have a simple question here.
How can I understand if a pointer points to something, or is just initialized ?
I tested the following code :

int *test1;
if(test1 == 0)
int b = 1;
QString *test;
if(test == 0)
int a = 2;


and also

int *test1;
if(test1 == NULL)
int b = 1;
QString *test;
if(test == NULL)
int a = 2;

But it never enters the if clause.
How can I check this ?

Thank you in advance !
Last edited on
You must always initialize your pointers.
1
2
3
4
5
6
7
8
9
10
int *test1 = NULL;

if (test1)
  {
  cout << "test1 points to something\n";
  }
else
  {
  cout << "test1 does not point to anything\n";
  }

Please use [code] blocks, and avoid examples that use Qt or other non-standard libraries when unnecessary.

The pointer to a QString must likewise be initialized to NULL or to an actual QString:
1
2
3
4
5
6
7
8
9
10
QString *test = new QString;

if (test)
  {
  *test = "Hello world!\n";
  }
else
  {
  fooey();
  }

Hope this helps.
Ah, I see. Thank you Duoas. :)
You said "always", do you mean it will not be auto initialized also if it's a member of a class ?
If I have
1
2
3
4
5
class Class { 

private:
    MyClass*test;
}
,
should I initialize this in the constructor in the .cpp ? For example test = NULL; ?

Regards,
Patric

p.s.: For the QString, sorry it was a mistake. I forgot to delete it from my post.
Always.

Duoas: I thought you didn't like NULL...
Last edited on
Me? I don't like macros like ZERO and ONE... but I use NULL all the time.

I suppose I like to read some type information in values... I tend to use true and false (or TRUE and FALSE) over 1 and 0... just because the booleanness is important...
ironically, NULL is just about the only named constant I don't use!
Well, NULL is unfortunately one of the more abused macros... a lot of old systems have it #defined as something weird (like ((void*)0L) or worse) and it breaks some compilers...

I just require that the build environment be sane (#define NULL 0 ). There are pros and cons either way, and it is a religious issue for many, but so long as your build environment gives me a proper type-promotable zero that compiles with strict ISO-C and C++ without significant grief then I just don't care... I prefer to read that I'm looking at a null pointer, rather than wonder about what foo = 0 means in the middle of some oddball function.

And, like TRUE and FALSE, the NULL macro should not be used except as an assignment rvalue. Don't use it in comparisons and the like -- let the language do the proper handling:
if (ptr)
instead of
if (ptr != NULL) if (NULL != ptr)
etc, because it will break on older, stupider systems.

The preprocessor was designed to make some tasks easier -- not to promote radical language modification or code obfuscation. A lot of weird macros usually indicates bad code.

My $0.02.
Thank you guys. :)

Best regards
Topic archived. No new replies allowed.