C++

C++ 1일차

Muru 2023. 12. 18. 15:09

전방선언

using namespace std;

//전방선언: forward declaration
int add(int a, int b);
int mulitiply(int a, int b);
int subtract(int a, int b);

int main()
{
	cout << add(1, 2) << endl;
	cout << mulitiply(3, 4) << endl;
	cout << subtract(7, 5) << endl;

	return 0;
}

//정의: definition 
int add(int a, int b)
{
	return a + b;
}

int mulitiply(int a, int b)
{
	return a * b;
}

int subtract(int a, int b)
{
	return a - b;
}

 


 

네임스페이스

#include <iostream>

//이름을 유지하는 방법: namesapce
namespace MySpace1
{
	int doSomething(int a, int b)
	{
		return a + b;
	}
}

int doSomething(int a, int b)
{
	return a * b;
}

using namespace std;

int main()
{
	cout << MySpace1::doSomething(3, 4) << endl;
	cout << doSomething(3, 4) << endl;

	return 0;
}

매크로 사용법과 스탠다드 라이브러리 사용법

#include <iostream>
#include <algorithm>

using namespace std;

//매크로 define : 문서편집기
//#define MY_NUMBER "Hello, World"
#define MAX(a, b) (((a) > (b)) ? (a) : (b))

int main()
{
	// << MAX(1 + 5,3) << endl;
	cout << std::max(1 + 3, 2) << endl;
	return 0;
}

 

 


 

 

 

#include <iostream>
#include <algorithm>

using namespace std;

//#define LIKE_APPLE

//전처리기: 빌드전에 하는것
//빌드 시작전 Window인지 Linux인지 등 확인을 위해 사용

int main()
{
#ifdef LIKE_APPLE
	cout << "Apple" << endl;
#endif

#ifndef LIKE_APPLE
	cout << "Orange" << endl;
#endif

	return 0;
}

 

 


 

기본자료형소개 (Fundamental Data Types)

초기화 방식 3가지

copy initialization

direction initialization

uniform initialization

#include <iostream>

int main()
{
	using namespace std;

	bool bValue = false;
	char chValue = 65;
	float fValue = 3.141592;
	double dValue = 3.141592;

	//직접 만든 데이터 타입 초기화시 자주 사용: 객체지향시 중요함
	int i = (int)3.1415;	// copy initialization
	int a((int)123.45);		// direction initialization
	int b{ 4 };				// uniform initialization

	int k = 112, l(992), m{ 423 };

	return 0;
}

 

 


오버플로우

연습

#include <iostream>
#include <cmath>
#include <limits>

int main()
{
	using namespace std;

	short s = 1;	//2byte = 2 * 8 bits = 16bits
	int i = 1;		//4byte = 4 * 16 bits = 32bits

	cout << std::pow(2, sizeof(short) * 8 - 1) << endl;
	cout << std::pow(2, sizeof(int) * 8 - 1) << endl;

	s = std::numeric_limits<short>::max();
	cout << "short: " << s << endl;
	
	s = s + 1;
	cout << s << endl;

	i = std::numeric_limits<int>::min();
	cout << "int: " << i << endl;

	i = i - 1;
	cout << i << endl;

	return 0;
}

//컴퓨터는 2진수이므로 비트 표현을 위해 std:pow(2를 붙임)
//sizeof(short, int)로 2와 4를 반환
// 2 * 16 - 1 = 32768
// 2 * 32 - 1 = 21억 ~

 


부동소수점

#include <iostream>
#include <limits>

int main()
{
	using namespace std;

	float f(3.14);	//3.14 = 31.4 * 0.1;

	cout << 3.14 << endl;
	cout << 31.4e-1 << endl;	//e-1 : 10의 -1제곱
	cout << 31.4e-2 << endl;	//-2제곱 = 0.01
	cout << 31.4e1 << endl;		//10의 1제곱
	cout << 31.4e2 << endl;		//10의 2제곱

	return 0;
}

 

 

 

setprecision을 해야만 보이는 자그마한 오차

]

 


#include <cmath>

//숫자이냐 아니냐? 0 or 1
cout << psinf, neginf, nan << " " << std:isnan(nan) <<endl;