0

I was trying to find the order of evaluation inside if clause when more than 2 conditions are specified. I found multiple results to talk about how 2 conditions are evaluated. My questions is when I have something like,

it=seqMap.find(a);

if( a !="" && it==seqMap.end() || isEven )
{
//Do something
}

I understand that this is not the right way to write code and braces are important but I am trying to understand how this will work, out of curiosity.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
codeworks
  • 149
  • 1
  • 15

3 Answers3

2

The built-in boolean operators impose a strict sequencing. They have shortcut evaluation where the second argument is not even evaluated if the first one determines the outcome. This is important in cases where evaluation of the second argument could have Undefined Behavior.

User defined boolean operators do not, as a rule, provide shortcut evaluation.

It's possible to emulate the effect but C++ doesn't really support this. C# does.


A && B || C

… is parsed as

(A && B) || C

… because && effectively has higher precedence than ||.

However, the C++ grammar is not defined in terms of precedence. Rather it's designed to emulate a precedence, which then appears as an emergent feature of the grammar. And this means that a naïve precedence view in some cases can indicate an incorrect parse, so use precedence reasoning with care.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • 1
    Off-topic but I think it can be useful to know. When I went to Heriot-Watt University in the late 1980's, a lecturer claimed, in his lecture, that Pascal had shortcut evaluation but that C did not. I stood up and challenged that: I knew Pascal extremely well at that time, and I knew the basics of C. He puffed and huffed and responded that he really knew what he was talking about because he was writing a book. He then went and fetched his manuscript. When he came back he quoted himself triumphantly, that Pascal did not have shortcut evaluation, but C had! And pretended that that's what he said. – Cheers and hth. - Alf Nov 16 '16 at 09:33
0

It will first evaluate

 a !="" && it==seqMap.end()

If a !="" evaluates to false then it will check

a !=""|| isEven 

Otherwise if a !="" evaluates to true then, it==seqMap.end() will be evaluated and finally the the answer of a !="" && it==seqMap.end() will be OR'ed with isEven

Issac Saji
  • 106
  • 6
0

In C++ the logical AND operator has higher precedene than the logical OR operator.

Also the logical AND and OR operators have shortcut evaluation. If the first condition of AND is false, then the second condition will not be evaluated. Similarly, if the first condition of OR is true, then the second condition will not be evaluated.

For further reference on operator precedene: http://en.cppreference.com/w/cpp/language/operator_precedence

Slagathor
  • 47
  • 7