0

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?

2
  • 3
    Just a note on the side, the null pointer needs not be represented as a zero in your hardware, but the compiler factors out this complication. Commented Aug 8, 2009 at 7:36
  • At its heart a pointer is just an unsigned integer (mathematical expression here), describing an address in memory. Some of them are special. For instance, the address 0 is the nullptr. And, being a number, it can be implicitly cast to bool. Usually 0 casts to false, and every other value to true. Hence, if(p) .. may be employed to guard against proper nullptrs. Of course, this does not prove if a p!=0 is properly defined. Commented Sep 9 at 11:19

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Compiler code generation bug? Or the segfault was really somewhere else?
1

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?

3 Comments

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.
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.
He is referring, I assume, to the 'pointer to member of class' type, that have strange 0 comparison.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.