๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
BackEnd๐ŸŒฑ/Java

[Java] ์‡ผํŠธ-์„œํ‚ท (Short-Circuit)

by dkswnkk 2022. 3. 8.

์‡ผํŠธ-์„œํ‚ท (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๋กœ ์ถœ๋ ฅ์ด ๋  ์ค„ ์•Œ์•˜๋Š”๋ฐ ์•„๋‹ˆ๊ธธ๋ž˜ ์ฐพ์•„๋ณด๋‹ค๊ฐ€ ์‡ผํŠธ์„œํ‚ท์— ๋Œ€ํ•ด ์•Œ๊ฒŒ ๋˜์–ด ์ •๋ฆฌํ•˜๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€