8.4 Arithmetic conversions

주홍영·2022년 3월 12일
0

Learncpp.com

목록 보기
80/199

https://www.learncpp.com/cpp-tutorial/arithmetic-conversions/

예를들어 2 + 3.5 를 하면 이 expression의 return은
무슨 타입일까?

참고로 저런 경우 int형 value가 암묵적으로 double로 함께 간주되어 double이 return 된다
이러한 변환을 arithmetic conversion 이라 한다

본래 operator는 same type의 operand를 요구한다
하지만 implicit하게 conversion을 해주어 일단 이상없이 프로그램이 도와주도록 만들어준다
그리고 이러한 타입간의 우선순위가 존재한다

The usual arithmetic conversion rules

  • long double (highest)
  • double
  • float
  • unsigned long long
  • long long
  • unsigned long
  • long
  • unsigned int
  • int (lowest)
    위의 순서로 우선순위를 가지고 있다

따라서 아래와 같은 특이한 사례도 있다

#include <iostream>
#include <typeinfo> // for typeid()

int main()
{
    short a{ 4 };
    short b{ 5 };
    std::cout << typeid(a + b).name() << ' ' << a + b << '\n'; // show us the type of a + b

    return 0;
}

위 코드의 출력 결과는 다음과 같다

int 9

앞서 언급한 arithmetic conversion rule 도표의 우선순위에 short는 존재하지 않는다
따라서 가장 낮은 우선수위의 int로 변환된다

profile
청룡동거주민

0개의 댓글