Will the second be evaluated if the first is NULL?

W

William Payne

Consider the following code:

struct foo
{
char* bar;
};

// fooptr is of type foo*
if(fooptr != NULL && fooptr->bar != NULL)
{
cout << fooptr->bar << endl;
}

Is the if-statement safe, meaning it won't try to evaluate fooptr->bar if
fooptr is NULL? Can I make sure it is evaluated from left to right or should
I have nested if-statements instead?

Thanks for any replies

/ William Payne
 
K

Karl Heinz Buchegger

William said:
Consider the following code:

struct foo
{
char* bar;
};

// fooptr is of type foo*
if(fooptr != NULL && fooptr->bar != NULL)
{
cout << fooptr->bar << endl;
}

Is the if-statement safe, meaning it won't try to evaluate fooptr->bar if
fooptr is NULL? Can I make sure it is evaluated from left to right or should
I have nested if-statements instead?

In x && y, it is guaranteed that y is not evaluated if x is already false.
Same for x || y : if x is already true, y is not evaluated at all.

Which books are you using, that do not mention 'shortcut evaluation' ?
 
J

Julie

William said:
Consider the following code:

struct foo
{
char* bar;
};

// fooptr is of type foo*
if(fooptr != NULL && fooptr->bar != NULL)
{
cout << fooptr->bar << endl;
}

Is the if-statement safe, meaning it won't try to evaluate fooptr->bar if
fooptr is NULL? Can I make sure it is evaluated from left to right or should
I have nested if-statements instead?

You're golden -- yes, the statement is safe.

The behavior is called 'short circuit', and evaluated left to right.
 
W

William Payne

Karl Heinz Buchegger said:
In x && y, it is guaranteed that y is not evaluated if x is already false.
Same for x || y : if x is already true, y is not evaluated at all.

Which books are you using, that do not mention 'shortcut evaluation' ?

Thanks for the quick reply, Karl. No need for a nested if-statement then,
just as I thought. And to answer your question: I don't have access to a C++
text except Josuttis Standard Library Book at the moment. =/

/ William Payne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top