Tuesday 8 November 2011

What does it mean when a pointer is used in an if statement? in C programming

What does it mean when a pointer is used in an if statement?

Any time a pointer is used as a condition, it means “Is this a non-null pointer?” A pointer can be used in an
if, while, for, or do/while statement, or in a conditional expression. It sounds a little complicated, but it’s
not.
Take this simple case:
if ( p )
{
/* do something */
}
else
{
/* do something else */
}
An if statement does the “then” (first) part when its expression compares unequal to zero. That is,
if ( /* something */ )
is always exactly the same as this:
if ( /* something */ != 0 )
That means the previous simple example is the same thing as this:
if ( p != 0 )
{
/* do something (not a null pointer) */
}
else
{
/* do something else (a null pointer) */
}

This style of coding is a little obscure. It’s very common in existing C code; you don’t have to write code that
way, but you need to recognize such code when you see it.

Cross Reference:

VII.3: What is a null pointer?

No comments:

Post a Comment