Reputation: 14823
I am looking at the implementation of an algorithm proposed at Build the binary search tree from inorder and preorder traversals.
I think the implementation is in c++ and I have a question about this one line Node * temp = (Node *)malloc(sizeof(Node));
and the evaluation of its following if
condition as seen in a block like this :
Node * temp = (Node *)malloc(sizeof(Node));
if(temp){
//do some stuff
//conditionally return a Node
}
return NULL
Node is presumably a binary tree node. Its implementation is not shown, but how is that if(temp)
condition working such that the last return NULL
is ever reached?
Upvotes: 0
Views: 422
Reputation: 1105
Actually the code structure should be,
Node * temp = (Node *)malloc(sizeof(Node));
if( temp != NULL ){
//do some stuff
//conditionally return a Node
}
else
{
return NULL;
}
you should not follow the structure you shown for code readability.
Upvotes: 0
Reputation:
In C prior to C99, there wass no specially designated boolean type. A scalar type was, and still can be used instead, such as int
or a pointer like, in your case, Node*
. A zero value is equivalent to false
, a nonzero value is equivalent to true
.
So, in your example, the pointer temp
is the condition in the if
statement. That means that the code in the if
will execute if the value of temp
is true
, i.e. doesn't equal zero (NULL
).
Upvotes: 1
Reputation: 18371
the if
block is executed whenever the condition statement (which is temp
in your case) is not equal to zero. In C the NULL
pointer has a numerical value of zero. So if temp
is NULL
, the if
block will not be executed.
Upvotes: 1
Reputation: 505
if(temp)
means if (temp!=NULL)
, which essentially means that if the Node* temp was successfully malloc'ed and returned from malloc, then enter the if
block of code. Unless there is code to return something in the if
block (which would then exit the program), the return NULL
statement will execute.
Upvotes: 2
Reputation: 63912
The conditional in an if
is considered false if it evaluates to 0
, and true if it's non-zero.
how is that
if(temp)
condition working such that the lastreturn NULL
is ever reached?
It's reached if temp
is NULL
, which evaluates to 0
.
Upvotes: 1