If Else vs && ||

Is there any difference between coding with if else or && and || operators.

For example, in the if-else style, I can write this code

for( var i = 0; i < 1000000000; i ++ ) {
    if( i % 2 == 0 ) {
        f1();
    } else {
        f2();
    }
}

Both in && and || style I can get the same result with this code

(( i % 2 == 0 ) && (test1() || true)) || test2();

I tested them in JS, they work at about the same time, but I did not test them in C ++. Perhaps this depends on the compiler or language.

Is there any difference in speed? Or is there any difference whatsoever?

thanks

+4
source share
3 answers

, , , , , - . , . - , , .

+6

, , if, .

( ), 50% , 100%.

.. , .

+4

(test1() || true)

, , , test1 void , bool, , , .

.

: KISS - Keep It Simple Stupid.:)

, .

, , . , .

,

i % 2 == 0 ? ( void )test1() : ( void )test2();

, JavaScript void

i % 2 == 0 ? test1() : test2();

++.

+4

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


All Articles