5.11 자료형 변환 Type conversions

공기훈·2021년 8월 22일
0

홍정모의 따배씨

목록 보기
24/49
  • Promotion
    작은 자료형을 큰 자료형에 집어넣는 것.
  • Demotion
    큰 자료형을 작은 자료형에 집어넣는 것.
#include <stdio.h>

int main()
{
    /* promotions in assignments */
    short s = 64;
    int i = s;

    float f = 3.14f;
    double d = f;

    /* demotion in assignments */
    d = 1.25;
    f = 1.25;
    // f = 1.123f;
}

ranking of types in operations

일단 실수가 정수보다 ranking이 높다.

실수형

long double > double > float

정수형

unsigned long long, long long
unsigned long, long
unsigned, int
short int, unsigned short int
signed char, char, unsigned char
_Bool

d = f + 1.234;
1.234는 double이므로, float를 double로 바꿔서 계산하고 double에 대입하므로 문제가 없다.
f = f + 1.234;
하지만, 1.234가 double이므로 f + 1.234도 double이 되고, double 값을 float에 집어넣으려 하기 때문에 문제가 생긴다.

automatic promotion of function arguments

  1. Functions without prototypes
  2. Variaic functions (ellipsis)

casting operators

    int d, i;

    d = (double)3.14f;
    i = 1.6 + 1.7;
    i = (int)1.6 + (int)1.7;
    // (int)1.6 는 1, (int)1.7도 1이므로 i = 2가 된다.

more example

#include <stdio.h>

int main()
{
	char c;
	int i;
	float f;

	f = i = c = 'A'; //65 // Warning : conversion from 'int' to 'float', possible loss of data
	printf("%c %d %f\n", c, i, f);
	c = c + 2; // 'C', 67
	i = f + 2 * c; //65.0f + 2 * 67 // Warning : conversion from 'float' to 'int', possible loss of data
	printf("%c %d %f\n", c, i, f); // 199
	
	c = 1106; // demolition, 1106 = 0b10001010010, 0b01010010 = 1106 % 256 = 82 = 'R'
	// 나머지 연산자를 적용한 것과 같다.
	printf("%c\n", c); 
	
	c = 83.99; // 절삭 -> 83
	printf("%c\n", c);

	return 0;

}
profile
be a coding master

0개의 댓글