컴퓨터 언어/C++

Primitive Built-In Types

redsiwon 2020. 7. 23. 07:31
int i = 13;
bool b;
if (b = i) // true
	std::cout << b << std::endl; // 1
double d = .0; // 0. also possible
if (!(b = d)) // false
	std::cout << b << std::endl; // 0

논리형 bool

다른 산술타입에서 bool로 형변환하는 경우

=> 0이면 false, 아니면 true

 

bool에서 다른 산술타입으로 형변환하는 경우

=> true는 1로, false는 0으로

 

d = 12.34567;
i = d;
std::cout << i << std::endl; // 12

d = i;
std::cout << d << std::endl; // 12

부동소수점형 floting-point

부동소수점형을 통합형으로 형변환

=> 소수점 이하는 날라간다. (반올림이 아니라 아예 삭제)

 

통합형에서 부동소수점형으로 형변환

=> 소수점 이하는 0으로 채워진다.

 

 

unsigned int ui1 = 10;
unsigned int ui2 = -1; // 2^32 - 1 (4294967295)
std::cout << ui2 - ui1 << std::endl; // 2^32 - 11 (4294967285)
i = -22;
std::cout << ui1 + i << std::endl; // 10 + 2^32 - 22 => 2^32 - 12 (4294967284)

long long ll = (long long)INT32_MAX << 1; // 2^32 - 2 (4294967294)
ll = INT32_MAX * 2LL; // same as the one above;
i = ll; // 2^31 - 1 + 2^31 - 1 => -2^31 + 2^31 -2, overflow
std::cout << ll << " " << i << std::endl; // 4294967294 -2

비부호지정자 unsigned

정수형, 문자형에 사용 가능

 

범위를 벗어난 경우

=> 크기 내에서 modulo 연산의 결과값을 갖는다.

(signed에서는 원칙상 undefined인데, 구현상 비슷하게 언더플로, 오버플로 현상 발생)

 

signed와 함께 연산하는 경우

=> unsigned로 형변환된 후 연산 수행

 

if ((18 == 022) && (022 == 0x12))
	std::cout << "decimal octal hexademical" << std::endl;

if ((3.141592 == .0003141592e4) && (.0003141592e4 == 3141592E-6))
	std::cout << "decimal point & scientific notation" << std::endl;
    
// 123. ==> 123.0
// .123 ==> 0.123

정수형/실수형 상수(리터럴 Literal)

정수형 리터럴은 10진수, 8진수, 16진수로 표현할 수 있다.

기본형은 int이다.

만약 다른 타입과 연산하면 형변환이 일어날 수 있다.

 

실수형 리터럴의 기본형은 double이다.

실수형 리터럴은 소수점을 찍고 좌우로 생략이 가능하다.

또한, a * 10^b 의 형태로 표현할 수 있다.

이때 e 또는 E를 사용할 수 있고 우측에 b의 값을 쓴다.

 

char c = 'c'; // character literal
const char* cstr = "c-style string"; // A null character will be appended to every string literal.
std::string s = "c++ string"; // C++ strings don't have a last null charater.

std::cout << "string literals " "seperated only by "
	     "spaces, newlines, or tabs"        " are "
	     "concatenated into a single string literal."
	  << std::endl;
// output: string literals seperated only by spaces, newlines, or tabs are concatenated into a single string.

문자형 상수(리터럴 Literal)

문자형 리터럴은 단일 character literal과 여러 개의 charater literal의 배열인 string literal이 있다.

단일 문자 리터럴은 작은 따옴표로 감싼다.

문자열 리터럴은 큰 따옴표로 감싼다.

 

문자열 리터럴은 마지막에 '\0' (null charater) 하나가 추가된다.

C++의 string 객체를 문자열 리터럴을 통해 생성하면 널 문자는 저장되지 않는다.

띄어쓰기, 탭, 개행으로 띄어진 인접한 두 문자열 리터럴은 하나의 문자열 리터럴로 합쳐진다.

 

상수는 변수와 다르다.

상수는 값 그 자체이다.

변수는 값을 저장하는 저장 공간이다.

 

계속 추가될 예정..