본문 바로가기

프로그래밍 언어/C++

integral conversion에 대해

반응형

conversion의 설계 개념

C++의 conversion를 정의할 때, 직교하는 3 요소, value category, cv-qualification, data representation를 설계 개념으로 사용한다. conversion를 설계할 때, 요소 중 하나만을 변형하고, 다른 요소를 변형하지 않는다. 어떤 이유로, 예를 들어 하위 호환성을 위해, 설계 개념을 위반할 때는 관련된 특수 조항을 스펙 문서에 별도로 명시한다.

integral conversions

data representation 요소를 변형하기 위해 설계한 conversion이다. data representation를 변경하기 때문에, conversion rank로 분류된다. 또한 일반적으로 value category이나 cv-qualification를 변경하지 않는다.

integral conversionprvalue category에서 prvalue category로 변환을 정의한다.

integer typeprvalue category다른 integer typeprvalue category로 변경할 수 있다. unscoped enumeration typeprvalue categoryinteger typeprvalue category로 변경할 수 있다.

소스 타입이나 목적이 bool type이 아닌 경우, 목적 integer type 결과는 소스 타입 2^N modulo 연산 결과는 같다. N은 목적 타입의 width를 의미한다. 따라서 integral conversions는 손실 변환이다.

#include <print>
#include <limits.h>

int main(int argc, char* argv[]) {
    int modulo = std::pow(2, CHAR_BIT);
    int s = modulo + 10;

    unsigned char a = s;
    std::println("s:{} a:{}", s, a);
    std::print("modulo : {0}\n  a % {0} : {1}\n  s % {0} : {2}", modulo, a % modulo, s % modulo);
    return 0;
}
[출력 결과]
s:266 a:10
modulo : 256
  a % 256 : 10
  s % 256 : 10

bool typeprvalue category다른 integer typeprvalue categoryfalse0, true1로 변경할 수 있다.
다른 integer typeprvalue category에서 bool typeprvalue category로 변환은 boolean conversion 규칙을 따른다.

integral promotion conversionboolean conversionintegral conversion에서 제외된다.

반응형