[Java] μΌνΈ-μν· (Short-Circuit)
μΌνΈ-μν· (Short-Circuit)
μΌνΈμν·μ΄λ λ Όλ¦¬ μ°μ°μμ λ νΌμ°μ°μ μ€ μ΄λ νμͺ½λ§ 'μ°Έ'μ΄λ©΄μ μ°μΈ‘ νΌμ°μ°μμ κ°μ νκ°νμ§ μκ³ λ°λ‘ κ²°κ³Όλ₯Ό μ»λ νμλ₯Ό λ§ν©λλ€. κ·Έλμ κ°μ 쑰건μμ΄λΌλ νΌμ°μ°μμ μμΉμ λ°λΌμ μ°μ°μλκ° λ¬λΌμ§ μ μμ΅λλ€.
μλ₯Ό λ€μ΄ μλμ κ°μ μ½λκ° μμ΅λλ€. κ³Όμ° μΆλ ₯ κ²°κ³Όλ μ΄λ»κ² λμ¬κΉμ?
// JAVA
public class Test {
public static void main(String[] args) {
int a = 0, b = 0;
if (a == 0 || ++b == 1) {
}
System.out.print(a + " " + b);
}
}
μ μ½λμ μΆλ ₯ κ²°κ³Όλ 0 0 μ΄ λμ΅λλ€.
μ€ν κ²°κ³Όμμ μ μ μλ―μ΄, λ λ²μ λ Όλ¦¬ μ°μ° νμλ bμ κ°μ μ¬μ ν 0μΈ μ±λ‘ λ¨μμμ΅λλ€. '||(OR)'μ κ²½μ°λ μ’μΈ‘ νΌμ°μ°μ (a==0)κ° μ°Έμ΄λΌμ μ°μΈ‘ μ°μ°μλ₯Ό νκ°νμ§ μκ³ λ°λ‘ λμ΄κ°κΈ° λλ¬Έμ λλ€. λ°λΌμ κ²°λ‘ μ μΌλ‘ κ°μ 쑰건μμ΄λΌλ νΌμ°μ°μμ μμΉμ λ°λΌμ μ°μ°μλκ° λ¬λΌμ§ μ μμ΅λλ€.
μ¦ μ°μ° κ²°κ³Όκ° 'μ°Έ'μΌ νλ₯ μ΄ λμ νΌμ°μ°μλ₯Ό μ°μ°μμ μμͺ½μ λμμΌ λ λΉ λ₯Έ μ°μ° κ²°κ³Όλ₯Ό μ»μ μ μμ΅λλ€.
κ·Έλ λ€λ©΄ JAVAλΏλ§ μλλΌ λ€λ₯Έ μΈμ΄λ€λ Short-Circuitμ μ§μν κΉμ?
Short-circuit evaluation - Wikipedia
Programming language construct Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if
en.wikipedia.org
μν€νΌλμμ Support in common programming and scripting languages λΆλΆ λͺ©μ°¨λ₯Ό μ΄ν΄λ³΄λ©΄ Short-Circuitμ μ§μνλ μΈμ΄ λͺ©λ‘μ νμΈν μ μμ΅λλ€. μ°λ¦¬κ° μκ³ μλ μΈμ΄μΈ C, C++, JAVA, Kotlin, Python, JSκ³Ό κ°μ μΈμ΄λ€λ κΈ°λ³Έμ μΌλ‘ Short-Circuitμ μ§μν¨μ μ μ μμ΅λλ€.
νκ³
int main(){
int a = 0, b = 0;
if(a==0 || ++b == 1);
cout<<a<<' '<<b;
}
μ μ½λκ° λΉμ°ν 0 1λ‘ μΆλ ₯μ΄ λ μ€ μμλλ° μλκΈΈλ μ°Ύμ보λ€κ° μΌνΈμν·μ λν΄ μκ² λμ΄ μ 리νκ² λμμ΅λλ€.