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
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 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 && .
Types of Logical Operators in C We have three major logical operators in the C language: Logical NOT (!) Logical OR (||) Logical AND (&&)
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 .
Yes, it is a guaranteed feature called short circuit evaluation.
Likewise, an expression false && expression
will never evaluate the right expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With