Reputation: 135
This is regarding a small confusion regarding pointers in C++ while comparing them to NULL. Here's the code :
struct node
{
int data;
struct node *left;
struct node *right;
}
int main()
{
struct node *p;
if(p!= NULL)
printf("line1\n");
else
printf("line2\n");
struct node *temp;
if(temp == NULL)
printf("line3\n");
}
The output:
line2
line3
While for the following piece of code:
struct node
{
int data;
struct node *left;
struct node *right;
}
int main()
{
struct node *p;
if(p!= NULL)
printf("line1\n");
else
printf("line2\n");
struct node *temp;
}
This is the output:
line1
Can anyone please explain the reason of such occurrence ?
Upvotes: 1
Views: 158
Reputation: 124632
You declare a pointer, but you do not initialize it. It could take on any value, i.e., it is not guaranteed to be NULL
. Of course, it could be NULL
(0), but again, that cannot be counted upon.
The value of an uninitialized variable is indeterminate unless it has static storage duration.
Upvotes: 2
Reputation: 123448
auto
variables (i.e., local variables not declared static
) such as p
and temp
are left uninitialized, so their value is indeterminate (essentially, whatever bit string is left in that particular memory cell from a previous operation, which may or may not be a valid value for the given type). Never try to dereference an uninitialized pointer.
Variables declared at file scope (outside of any function block) or with the static
keyword are initialized as follows:
If you change the declaration of p
to
static struct node *p;
then p
would be initialized to NULL. If you don't want to declare p
as static
, then you'll have to initialize it as part of the declaration:
struct node *p = NULL;
Upvotes: 2
Reputation: 612854
You are reading an uninitialized variable. That is undefined behaviour. Basically, anything can happen. If you turned on your compiler warnings, the compiler would have told you exactly that.
I suspect you believe that your local variables will be initialized automatically. That is not the case. You must initialize them before reading them.
Upvotes: 2
Reputation: 59997
You need to give the p
amd temp
values - as you have not they can contain anything.
Upvotes: 0