tags:

views:

246

answers:

2

I'm not sure if my understanding of C++ is wrong.. I've read that 1) all non-zero values are equivalent to TRUE, and zero is equivalent to FALSE; 2) null pointers are stored as zero.

Yet code like this:

void ViewCell::swapTiles (ViewCell *vc) {
    ViewTile *tmp = vc->tile();
    [stuff ...]
    if (tmp) addTile(tmp);
}

Gives me a segfault from dereferencing a null pointer, but

if (tmp != 0) addTile(tmp);

works fine. Any idea why?

+8  A: 

For a pointer, p and (p != 0) are exactly equivalent. If it gives you a segfault, then either it's not a plain pointer, or the problem is elsewhere

Pavel Minaev
yeah, I think you're right. after modifying some other parts of the code my problem seems to be gone. not quite sure how it happened in the first place though.
int3
Compiler code generation bug? Or the segfault was really somewhere else?
pjc50
+1  A: 

C++ 0 pointers are not necessarily stored as an all zero bit pattern, but the token 0 is always interpreted as the 0 pointer if the compiler thinks it's a pointer, and the integer 0 is always coerced to the 0 pointer (with possibly a different bit pattern) if the compiler thinks it's an integer that needs to be type converted. And pointers to different things can have different sizeof, which can also be a different sizeof than integers. But you can see how it all works out. Usually. Clear?

That muddies the water so much it is worth deleting. What you say may be technically true but you explain it so badly in terms of the original question it is confusing for new people. Either re-factor or delete.
Martin York
An integer 0 is not always coerced to a null pointer. For example, `int n = 0; void* p = (void*)n;` is U.B., and in particular needs not make `p` a null pointer. Only an integral literal 0 can be treated as a null pointer as described.
Pavel Minaev