Conditional Statement using Pointers

Hi all,
Are there any disadvantages of using statements such as

1
2
3
4
5
6
7
8
double *p;
//
// ... some manipulations on p
//
if(p){
}
else{
}


I have never run into any problems yet. But can there be scenarios where statements like this can introduce bugs in the code ?
No.
What if the pointers points to user defined classes ? I suppose the real question here is that does C++ guarantee that a null pointer will always translate to a false boolean ? Also, what if the pointer is uninitialized ? So I forget to set the value to null before I call the conditional statement. Could that create a problem ?
Class?
Unless you have some fixed value (magic number) in the class you would have no way of knowing whether a non-zero pointer is valid.
Boolean?
Yes.
Uninitialized?
That will depend on what the compiler does.
Problem?
Yes, if you try to use the pointer and no if you don't use that pointer. But it is good practice to init the values of pointer to null.
Last edited on
Suppose that you do have that magic number, ¿how are you planning to use it?
Like
1
2
3
4
5
6
class thing {
   public:
      thing():magic(0xdeadbeef) {};

    uint32_t magic;
}

This way if you wanted
1
2
3
4
5
6
if (p && p->magic == 0xdeadbeef) {
    // All is well
}
else {
    // Not well 
}

This would help but you could still get a seg fault
Last edited on
But you are dereferencing a (possibly) invalid pointer. That alone could make it crash.
¿what if still past the test?
Yes that is true. You could still have a problem. But if the pointer is bad it's bad. At some point you have to believe that if you coded it correctly that if the pointer is not null that it is valid. If not then the code is wrong and it is better that you get a seg fault so that you can then fix it.

The hardest problems are when you modify a pointer and do it incorrectly which causes non-deterministic results.
Topic archived. No new replies allowed.