CS Study/C++

[C++] [3] 형식 변환 (type casting)

23학번이수현 2024. 12. 18. 01:48

0. Intro

- 코딩하다보면 변수타입을 변환해야할 순간이 존재한다.

- 변환하는 방식은 크게 두가지가 존재한다.

 

i) 암시적 형 변환(implicit cast) : 컴파일러가 자동으로 변경

ii) 명시적 형 변환(explicit cast) : 프로그래머가 수동으로 변경

 

1. 암시적 형 변환(implicit cast)

- 암시적 형변환은 작은 범위의 자료형에서 넓은 범위의 자료형으로 변환할 때 일어난다.

##### input #####

#include <iostream>
using namespace std;

int main() {
    float floatValue = 10.5;
    double doubleValue;
    int intValue;

    doubleValue = floatValue;
    intValue = floatValue;

    cout << "floatValue: " << floatValue << endl;    // 출력: 10.5
    cout << "intValue: " << intValue << endl;        // 출력: 10
    cout << "doubleValue: " << doubleValue << endl;  // 출력: 10.5

    return 0;
}

##### output #####
floatValue: 10.5
intValue: 10
doubleValue: 10.5

 

1.1. 숫자 변환(numeric conversion)

- floatValue --> intValue로 변환할 시 10.5가 10으로 데이터 유실이 발생한다. 이를 숫자 변환이라고 한다.

 - 크기가 더 작은 자료형으로 변환하는 것을 의미한다.

 

1.2. 숫자 승격(numeric promotion)

- floatValue --> doubleValue로 변환할 시 10.5 --> 10.5로 더 큰 부동 소수점 자료형으로 변환된다.

- 즉, 더 크기가 더 큰 자료형으로 변환하는 것을 의미한다. (데이터 유실은 발생하지 않는다.)

 

2. 명시적 형 변환(explicit cast)

##### Input #####
#include <iostream>
using namespace std;

int main() {
    double pi = 3.141592;
    int intValue;

    intValue = int(pi);

    cout << "Original pi:" << pi << endl;
    cout << "Converted pi:"<< intValue << endl;

    return 0;
}


##### Output #####
Original pi:3.14159
Converted pi:3

 

- int()처럼 프로그래머가 의도적으로 원하는 시점에서 형식을 변환할 수 있도록 하는 것을 '명시적 형 변환'이라고 한다.