while searching for an answer as to whether I should use Zero or Null, I came upon this one in another question here on SO from a user stroustup:
Should I use NULL or 0? In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
So NULL and 0 are the same that's cool. But I need a little more understanding here: Suppose I have the following (a random example from cprogramming.com):
struct node {
int x;
node *next;
};
int main()
{
node *root; // This won't change, or we would lose the list in memory
node *conductor; // This will point to each node as it traverses the list
root = new node; // Sets it to actually point to something
root->next = 0; // Otherwise it would not work well
root->x = 12;
conductor = root; // The conductor points to the first node
if ( conductor != 0 ) {
while ( conductor->next != 0)
conductor = conductor->next;
}
conductor->next = new node; // Creates a node at the end of the list
conductor = conductor->next; // Points to that node
conductor->next = 0; // Prevents it from going any further
conductor->x = 42;
}
Looking at the while ( conductor->next != 0)
line for example; It is my understanding that that spot in memory could have garbage values in it from previous use. When it is released from use by a program, it becomes available again. So how can you use integer zero as a value to compare against in order to check if you have reached the end of the linked list? Can you guarantee that that garbage value is zero? Why wouldn't it be...just a random garbage value?
So, is my understanding completely off, or in the midst of the process of releasing that block of memory by a previous program is that memory re-zeroed? In the past I have always used NULL, thinking that it was a magic keyword that knew whether it was looking at a zero or a garbage value. However, reading the above answer to someone else's question I see that is not true. I apologize for such a trivial question but every time I compare against NULL or zero in my applications to check for the existence of something it bothers me that it just works and I don't know why. Thank you for any light you can shed.