lundi 20 avril 2015

Do if statements break when they find something false in c++?

In java and c# the if statement will be evaluated until one of the conditions is false, after which it won't check the rest. This doesn't seem to be the case in c++.

example:

if(true && 
false/*java and c# do not check past this point*/ &&
true/*c++ evaluates this*/)
{
    code...
}

I ask because I was trying to check to see if a pointer was valid and if it had some element in it. Like so

if(pointer && *pointer->member == whatever)
{
    code...
}

It does not work unless I extrude the pointer check to another if statement, and I know anything that is not 0 in c++ evaluates to true. Am I correct as to why this is happening? Why is it this way?

Edit based on comments: Ok, so this is not the case, but in my program

if(pointer && *pointer->member == whatever)
{
    code...
}

didn't work because of invalid access because pointer was nullptr. But

if(pointer)
{
    if(*pointer->member == whatever)
    {
        code...
    }
}

works because the second if is not run. I don't get why this is different, which is why I thought maybe c++ didn't break like that.member is a pointer to an enum, and whatever is an enum type. Could that be why this didn't work?

Aucun commentaire:

Enregistrer un commentaire