본문 바로가기
언어 공부/C++

공용체(Union)

by 세희홍 2022. 6. 29.

공용체

#include  <iostream>
using namespace std;
//공용체는 가장 큰 멤버변수 크기로 메모리 할당
union JobUnion {
	char name[32]; //32bytes
	float salary; //4bytes
	int workerId; //4bytes
}uJob; 
struct JobStruct {
	char name[32]; //32bytes
	float salary; //4bytes
	int workerId; //4bytes
}sJob;
int main() {
	cout << sizeof(uJob) << endl; //32bytes 
	cout << sizeof(sJob) << endl; //40bytes (최소 40. OS가 할당)
	return 0; 
}

공용체는 가장 큰 멤버변수 크기로 메모리 할당을 한다. 

위의 JobUnion에서는 가장 큰 멤버변수의 합이 40bytes이므로, 40이상이 할당이 된다.(OS가 할당하기 때문에 달라질 수 있다.)

 

int main() {

	uJob.salary = 1.1;
	uJob.workerId = 1234;
	sJob.salary = 2.1;
	sJob.workerId = 44434;

	cout << uJob.salary << endl; // 1.7292e-42
	cout << uJob.workerId << endl;  // 1234
	cout << sJob.salary << endl; // 2.1
	cout << sJob.workerId << endl; // 44434

	return 0; 
}

실수 타입에 정수를 넣으면 uJob.salary에 쓰레기 값이 들어가게 된다.

 

union JobUnion {
	long salary; //4bytes
	int workerId; //4bytes
}uJob; 
struct JobStruct {
	long salary; //4bytes
	int workerId; //4bytes
}sJob;
int main() {

	uJob.salary = 11;
	uJob.workerId = 1234;
	sJob.salary = 21;
	sJob.workerId = 44434;

	cout << uJob.salary << endl; // 1234 같은 공간이기 때문에 11이 오버라이트
	cout << uJob.workerId << endl;  // 1234
	cout << sJob.salary << endl; // 21 별도의 공간에 할당
	cout << sJob.workerId << endl; // 44434

	return 0; 
}

uJob.salary에 11이 들어갔지만 같은 공용체 멤버변수인 workId가 오버라이트 하게 돼서  1234가 출력된다. 

공용체는 같은 공간을 사용하고, 구조체는 별도의 공간에 할당한다. 

요즘은 자원이 풍부하기 때문에 공용체는 잘 사용하지 않는다. 

'언어 공부 > C++' 카테고리의 다른 글

추상클래스  (0) 2022.07.04
열거체(enumeration)  (0) 2022.06.29
구조체(struct)  (0) 2022.06.29
다형성(Polymorphism)  (0) 2022.06.27
클래스 간의 관계: 의존  (0) 2022.06.26

댓글