All is well

[C++/ETC] `!!temp`와 `temp != nullptr` 비교 본문

C++/ETC

[C++/ETC] `!!temp`와 `temp != nullptr` 비교

D0YUN 2025. 2. 9. 10:25

 

while (!!temp) { 
    cout << temp->data << endl;
    temp = temp->next;
}

C++에서 while 문을 사용할 때, `while (!!temp)`와 `while (temp != nullptr)` 중 어떤 것이 더 적절할까요?

 

두 방식은 같은 동작을 하지만, 가독성코드 스타일 측면에서 차이가 있습니다.


`!!temp`와 `temp != nullptr` 비교

`temp != nullptr`

while (temp != nullptr) { 
    cout << temp->data << endl;
    temp = temp->next;
}

 

  • 가독성이 좋고 의미가 명확합니다.
  • `temp`가 `nullptr`이 아닐 때 반복을 수행한다는 의미가 명확합니다.
  • 일반적으로 C++에서 선호되는 스타일입니다.

`!!temp`

while (!!temp) { 
    cout << temp->data << endl;
    temp = temp->next;
}

 

 

  • `temp`가 `nullptr`이면 false, 그렇지 않으면 true가 됩니다.
  • `! `를 두 번 수행하여 `temp`를 불필요하게 논리형으로 변환하는 연산이 포함되어 복잡해집니다.
  • C 스타일의 관용적 표현이지만 C++에서는 직관성이 떨어집니다.

추천하는 방식

  • `while (temp != nullptr)` 또는 `while (temp)`를 사용하는 것이 더 적절합니다.
  • `while (temp)`도 충분히 직관적이지만, 명확성을 위해 `while (temp != nullptr)`을 선호하는 경우도 많습니다.
  • `while (!!temp)`는 불필요한 연산이 포함되므로 권장하지 않습니다.

예제 코드

#include <iostream>

using namespace std;

// 연결 리스트의 노드 구조체 정의
struct Node {
    int data;
    Node* next;
};

int main() {
    // 노드 생성
    Node n1, n2, n3;
    
    // 데이터 할당
    n1.data = 1;
    n2.data = 2;
    n3.data = 3;

    // 노드 연결
    n1.next = &n2;
    n2.next = &n3;
    n3.next = nullptr; // 마지막 노드는 nullptr을 가리켜야 함

    // 연결 리스트의 첫 번째 노드를 가리킬 포인터
    Node* head = &n1;

    cout << "< while (temp != nullptr) 방식 >" << endl;
    Node* temp = head;
    while (temp != nullptr) { // 권장 방식
        cout << temp->data << endl;
        temp = temp->next;
    }

    cout << "\n< while (temp) 방식 >" << endl;
    temp = head;
    while (temp) { // 이렇게만 해도 충분함
        cout << temp->data << endl;
        temp = temp->next;
    }

    cout << "\n< while (!!temp) 방식 >" << endl;
    temp = head;
    while (!!temp) { // 불필요한 연산 포함
        cout << temp->data << endl;
        temp = temp->next;
    }

    return 0;
}

 

 

 

실행 결과

 

 

 

'C++ > ETC' 카테고리의 다른 글

[C++/ETC] 미정의 동작(Undefined Behavior, UB)  (0) 2025.02.16