Is the “logic short circuit” dictated by the standard, or is it just used primarily as an optimization?

Consider this

Class* p = NULL;
if( p != NULL && p->Method() == OK ){

  // stuff
}

On all the compilers I worked with, this is completely safe. That is, the first part of the logical expression will be evaluated as false, and the call to the Method () method will not be made, since the evaluation of the second part is redundant.

Is it because most compilers optimize the evaluation of the second part or is it dictated behavior according to C / C ++ standards?

+3
source share
6 answers

. - , , .

, , SO .

+4

.

+4

C++ Standard 1998
5.14

& & . bool ( 4). true, true false . && & : , .

+4

, . ++. , , , , .

+2

, :

++ , , && || . , .

+2

, , .

, "" . - :

if (p != null) {
    if (p.getValue() == 3) {
        // do stuff
    }
}

It seems trivial, but try coding in a language that doesn't have one (like VB6), and you start to miss it a lot.

This is in language standards, as other answers mention, but only because something like this should be clearly indicated. What it can compile to optimized code is a side effect; currently a decent C or C ++ compiler will compile single-line or two-line statements evenly

+2
source

Source: https://habr.com/ru/post/1708178/


All Articles