[C++] &&의 단락평가

유빈·2024년 11월 10일
0

C++

목록 보기
10/12
post-thumbnail

자료구조 과제하다가 조건문 속의 조건들 순서를 바꿨는데, 결과가 달라졌다.



전체코드

#include <iostream>
#include <string>
#define MAX_CAPACITY 1000000 

using namespace std;

class ArrayStack {
private:
    char stack[MAX_CAPACITY];
    int top_pos = -1;

public:
    ArrayStack() {}

    bool full() {
        return top_pos == MAX_CAPACITY - 1;
    }

    bool empty() {
        return top_pos == -1;
    }

    void push(char digit) {
        if (full()) throw runtime_error("stack_full");
        stack[++top_pos] = digit;
    }

    void pop() {
        if (empty()) throw runtime_error("stack_empty");
        top_pos--;
    }

    char top() {
        if (empty()) throw runtime_error("stack_empty");
        return stack[top_pos];
    }

    // 각 자릿수들을 결합
    string combine(int len) {
        string biggestInt = "";

        for (int i = 0; i < len; i++) {
            biggestInt += stack[i];
        }

        return biggestInt;
    }
};

int main() {
    string N;  // 정수 N을 문자열로 입력받음 
    int K;     // 제거할 자릿수 개수 K를 입력받음 
    ArrayStack s;  // 각각의 자릿수 숫자를 저장할 스택 생성

    cin >> N;
    cin >> K;

    int digits = N.length() - K;  // 만들어야 하는 자릿수 개수

    for (char n : N) {
        // 스택의 맨 위 숫자가 현재 숫자보다 작고, 제거할 자릿수가 남아있다면 제거
        /*while (!s.empty() && s.top() < n && K > 0) {*/
        while (s.top() < n && K > 0 && !s.empty()) {
            s.pop();
            K--;
        }
        s.push(n); 
    }

    cout << s.combine(digits) << endl;

    return 0;
}


🍂 while (!s.empty() && s.top() < n && K > 0)


!s.empty() > s.top() < n > K > 0

위의 순서대로 조건들을 확인하게 된다.

따라서, 스택이 비어있는지 않는지 먼저 확인한다.

  • 스택이 비어있지 않다면, s.top() < n 조건을 평가한다.
  • 스택이 비어있다면, while문은 실행되지 않는다.

  • s.top() < n의 조건을 만족하면, K > 0 조건을 평가한다.
  • s.top() < n의 조건을 만족하지 않으면, while문은 실행되지 않는다.


🍂 while (s.top() < n && K > 0 && !s.empty())


s.top() < n > K > 0 > !s.empty()

위의 순서대로 조건들을 확인하게 된다.

따라서, s.top() < n 조건을 먼저 확인하게 된다.
그래서 스택이 비어있을 때도 s.top()을 호출하게 되어 런타임 에러나 무한 루프가 발생할 수도 있다.


따라서, 위와 같은 에러가 발생하지 않도록 && 연산자를 사용할 때는 조건들의 순서를 잘 생각해야 한다.

profile
🌱

0개의 댓글