Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confused by C++ logical OR (||) operator [duplicate]

Tags:

c++

Suppose I have two expressions left/right of || operator. I find if left expression is true, the right operator will never be called. For example, in my below code, when getRand returns true, I found Foo will never be called. I tested on XCode on Mac OSX, and wondering if it is a reliable feature of C++ we could rely on -- if left part of || is true, right part will never be called, or it is a special feature just for specific platform (e.g. OSX with XCode)? Post my code below, thanks.

bool Foo()
{
    std::cout << "I am called!\n";
    return false;
}

bool getRand()
{
    int random_variable = std::rand();
    std::cout << random_variable << '\n';

    return random_variable % 2 == 1;
}

int main(int argc, const char * argv[]) {

    if (getRand() || Foo())
    {
        std::cout<<"Hello World \n";
    }

    return 0;
}

thanks in advance, Lin

like image 993
Lin Ma Avatar asked Dec 02 '15 08:12

Lin Ma


People also ask

What is difference between || and && in C?

OR ( || ) - If EITHER or BOTH sides of the operator is true, the result will be true. AND ( && ) - If BOTH and ONLY BOTH sides of the operator are true, the result will be true.

Is && the same as C?

& is bitwise operator and, && is logical for example if you use two number and you want to use bitwise operator you can write & . if you want to use to phrase and you want to treat them logically you can use && .

Is && a logical operator in C?

Types of Logical Operators in C We have three major logical operators in the C language: Logical NOT (!) Logical OR (||) Logical AND (&&)

What is && operator in C?

The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 . The type of the result is int .


1 Answers

Yes, it is a guaranteed feature called short circuit evaluation.

Likewise, an expression false && expression will never evaluate the right expression.

like image 141
wallyk Avatar answered Sep 26 '22 01:09

wallyk