For example consider the following code. The pointer p
points to the variable a
that contains a nonzero value. Meaning, the condition should be true. So, if the program returns 1, I have no problem with that.
#include <iostream>
int main()
{
int *p, a = 1;
p = &a;
if(p)
{
return 1;
}
return 0;
}
But for the following program the result is same too. Though the pointer this time points to a variable that contains 0. So, the condition should be false, but it is not.
#include <iostream>
int main()
{
int *p, a = 0;
p = &a;
if(p)
{
return 1;
}
return 0;
}
So, what I am missing? Why the condition is always returning true? I am assuming the pointer has nothing to do with the value that it points to. Rather it is evaluating the condition on the basis of something else and I want to know that particular reason.
if (p)
does return true because if (p)
is shortcut to if (p != nullptr)
.
p
contains the memory address of the variable a
. In my machine that is 0x29fef8
. Since nullptr
is equivalent to 0
and p is not 0
thus the condition if (p != nullptr)
evaluates to true. Thus the condition always returns true.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments