변수와 기본적인 자료형

윤형찬·2020년 10월 19일
0

C++

목록 보기
2/4
post-thumbnail

기본자료형

출처 : http://www.cplusplus.com/doc/tutorial/variables/
  • 표에 "기울임 " 표시 글자는 생략이 가능
  • 1bit은 0이나 1이 들어갈 수 있는 한 칸
  • cout으로 char을 출력할 때, 메모리 사이즈가 작은 정수형 자료형으로써 char을 사용하고 싶으면 integer로 변환을 해주고 사용해야한다.
  • float은 32bits, double은 64bits
  • unsigned는 음수가 없는 자료형

<예제> exec.cpp

#include <iostream>

int main()
{
	using namespace std;

	//bool bValue = true;
	bool bValue = false;

	cout << (bValue ? 1 : 0 )<< endl;

	char chValue = 'A';
	cout << chValue << endl;
	cout << (int)chValue << endl;

	chValue = 65;
	cout << chValue << endl;

	float fValue = 3.141592f; // f를 안쓰면 수를 double 자료형으로 인식해서 컴파일 에러
	double dValue = 3.141592;

	cout << fValue << endl;
	cout << dValue << endl;

	//modern c++에 있는 기능
	auto aValue = 3.141592;
	auto aValue2 = 3.141592f;

	cout << aValue << endl;
	cout << sizeof(aValue) << endl;
	cout << aValue2 << endl;
	cout << sizeof(aValue2) << endl;

	return 0;
}

출력결과
0
A
65
A
3.14159
3.14159
3.14159
8
3.14159
4

C++의 변수 초기화 방법

  • 최근 트렌드는 변수를 사용하기 직전에 선언하는 것을 선호한다.
  • 디버깅하기 편함
  • 데이터와 기능을 묶어두면 리팩토링하기 편함 (빼내기 편함)
  1. int a = 123
    • copy initialization
    • 자료형에 맞지 않는 값으로 컴파일 시 경고만 띄운다.
    • int a = 3.14로 하면 형에 맞지 않는 값은 사라질수 있다고 경고만 한다.
  2. int a((int)3.14);
    • direct initialization
    • 1번과 마찬가지
  3. int b{ 123 };
    • uniform initailization
    • 자료형에 맞지 않는 값으로 컴파일이 안된다. (에러 발생)

한 줄에 여러 변수 선언 예제

int k = 0, l((int)456.2), m{ 123 };


정수형

영역 Category형 Type최소 크기기타
문자
Character
Char1 바이트
정수
Integer
short2바이트
int2바이트대부분 4바이트
long4바이트
long long8 바이트C99/C++11 type

자료형의 범위

  • 1 byte는 8 bits 다.
  • short는 2바이트까지 표현이 가능하다.
  • 16 bits 중 1bit은 부호를 표현하기 때문에 15bit로 수를 표현할 수 있다.
  • 따라서 -2^15 ~ 2^15 - 1 범위의 수만 표현 가능하다. (0도 포함되기 때문에 1 빼줌)
  • 자료형의 범위를 넘어가는 수를 저장하려하면 overflow가 발생한다.
  • 만약 unsigned short 였으면 0 ~ 2^16 - 1 수까지 표현이 가능하다.

예제 exer.cpp

#include <iostream>
#include <cmath>	// pow
#include <limits>	// max, min lowest 

int main()
{
	using namespace std;

	short	s = 1; // 2bytes = 2 * 8 bits = 16 bits

	cout << pow(2, sizeof(short) * 8 - 1) -1 << endl;
	cout << numeric_limits<short>::max() << endl;
	cout << std::numeric_limits<short>::min() << endl;
	cout << std::numeric_limits<short>::lowest() << endl;
    
    return 0;
}

출력 결과
32767
32767
-32768
-32768

  • short 자료형에 저장 할 수 있는 가장 큰 수 : 32767
  • short 자료형에 저장 할 수 있는 가장 작은 수 : -32768
	s = 32767;
	s += 1; // 32768

	cout << s << endl; // overflow

	s = std::numeric_limits<short>::min();
	s -= 1; // -32769
	cout << s << endl; // overflow

출력 결과
-32768
32767

overflow가 발생하여 저장하려던 값과 다른 값이 저장됨을 알 수 있다.



고정 너비 정수

  • 환경에 따라서 똑같은 int가 4 byte로 있는 경우도, 2 byte로 있는 경우도 있다.
  • 항상 같은 값을 같게 하기 위해 등장한 게 이 고정너비 정수이다.
  • 헤더파일 cstdint를 사용해야 한다.
  • iostream을 헤더파일로 사용할 경우에는 굳이 cstdint를 호출할 필요가 없다.

예제

#include <iostream>

int main()
{
	using namespace std;

	std::int16_t i(5);		// 16bit 데이터(short)로 바꿔준다.
	std::int8_t myint = 65;		// 8bit 데이터(char)로 바꿔준다.

	cout << myint << endl;

	std::int_fast8_t fi(5);		// 8bit 데이터 중 가장 빠른 자료형으로 선언한다
	std::int_least64_t fl(5);	// 적어도 64bit를 갖는 자료형으로 선언한다.

	return 0;
}


무치형 (Void, 보이드)

  • void는 메모리를 차지 하지 않기 때문에 자료형으로 선언 불가.
  • 리턴값이 없다.

예제

#include <iostream>

void my_function()
{

}

int main()
{
	//void my_void;

	int i = 123;
	float f = 123.456f;

	void *my_void;

	// 포인터 주소의 타입은 서로 같기 때문에 void 형식으로 캐스팅 가능
	my_void = (void*)&i;
	my_void = (void*)&f;

	return 0;
}


부동소수점 수

영역 Category형 Type최소 크기전형적인 크기
부동소수점
Floating point
float4 바이트4 바이트
double8 바이트8, 12 or 16 바이트
long double8 바이트8 바이트
  • float 의 경우 32 bit 중 1bit은 부호, 8bit은 지수, 나머지는 가수(0~1사이) 수 표현에 사용된다.
  • 참고
    - 수 표현
    • 31.4e-1 = 3.14
    • 31.4e-2 = 0.314
    • 31.4e1 = 314
    • 31.4e2 = 3140
<Code>
	cout << numeric_limits<float>::max() << endl;
	cout << numeric_limits<float>::lowest() << endl;

출력결과
3.40282e+38
-3.40282e+38
✎ float 자료형의 표현 범위

부동 소수점 연산시에 오차가 발생할 수 있다.

예제 exec.cpp

	float f(123456789.0f); // 10 significant digits
	cout << std::setprecision(9);
	cout << f << endl;
    
    
    	double d(0.1); // 10 significant digits
	cout << d << endl;
	cout << std::setprecision(17);
	cout << d << endl;
    
    
    	double d1(1.0);
	double d2(0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1);
	cout << setprecision(17);
	cout << d1 << endl;
	cout << d2 << endl;

출력결과
123456792

0.1
0.10000000149011612

1
0.99999999999999989

예상했던 것과 다른 결과물을 얻을 수 있다.

불리언 자료형과 조건문 if

  • bool은 0을 제외한 다른 모든 수(문자)는 true로 판단한다.

  • bool 결과를 1, 0말고 true, false로 보기
    - cout << std::boolalpha
    - 해제는 std::noboolalpha

  • 논리연산자
    - && : AND 연산
    - || : OR 연산
    - ! : not

  • if문

if (조건문)
{
조건문이 true일 때 실행
}
else
{
조건문이 false일 때 실행
}

예제 exer.cpp

#include <iostream>

bool isEqual(int a, int b)
{
	bool result = (a == b);
	return result;
}

int main()
{
	using namespace std;

	bool b1 = true;		// copy initialization
	bool b2(false);		// direct '''
	bool b3{ true };	// uniform ini
	b3 = false;

	cout << std::boolalpha;		
	
	cout << b3 << endl;
	cout << !true << endl;

	cout << (true || false) << endl;
	cout << (false && true) << endl;

	if (isEqual(3, 1))
	{
		cout << "This is True " << endl;
	}
	else
	{
		cout << "This is False " << endl;
	}

	return 0;
}

출력결과
false
false
true
false
This is False



문자형

  • 문자열을 정의할 때는 " "를 사용한다.
    - char c = "Hello, world";
  • 문자 하나를 정의할 때는 ' '를 사용한다.
    - char c = 'A';
	char c1(65);
	char c2('A');

	cout << c1 << " " << c2 << " " << int(c1) << " " << int(c2) << endl;

출력결과
A A 65 65

  • 캐스팅 (형변환)
	//C-style casting
	cout << (char)65 << endl;
	cout << (int)'A' << endl;

	//cpp style casting
	cout << char(65) << endl;
	cout << int('A') << endl;

	cout << static_cast<char>(65) << endl;
	cout << static_cast<int>('A') << endl;

출력결과
A
65
A
65
A
65

-추가-

  • 8진수 : 앞에 0 붙인다.
    - int x = 012 ➔ 10
  • 16진수 : 앞에 0x 붙인다.
    - int x = 0x12 ➔ 18
  • 2진수 : 앞에 0b 붙인다.
    - int x = 0b1010 ➔ 10
    - 0b101111111010 = 0b1011'1111'1010

  • 심볼릭 상수
    - 변하지 않는 값을 갖는 변수를 만들고 싶을 때 사용한다.
    - 변수를 초기화 할 때 const를 붙인다
    - const int a = 10 = int const a = 10
    - 상수는 따로 헤더파일을 작성하여 모아두는 것이 좋다.
profile
velmash

0개의 댓글