○union(共用体)

構造体と同じように扱えますが
一つのメモリの領域に複数の変数を割り当てています


#include <stdio.h>

union testUnion{
	char a;
	int b;
};

int main(){
	testUnion un;
	un.b = 0;
	un.a = -1;
	printf("%d\n%d\n",un.a,un.b);
	return 0;
}

処理結果
-1
255


■ビットを見ることが出来ます

#include <stdio.h>

union Field
{
	struct Bit
	{
		unsigned char b1 :1;
		unsigned char b2 :1;
		unsigned char b3 :1;
		unsigned char b4 :1;
		unsigned char b5 :1;
		unsigned char b6 :1;
		unsigned char b7 :1;
		unsigned char b8 :1;
	} bit;
	unsigned char ch;
};


int main(char* argv[])
{
	Field f;
	f.ch =254;

	printf("%d ",f.bit.b8);
	printf("%d ",f.bit.b7);
	printf("%d ",f.bit.b6);
	printf("%d ",f.bit.b5);
	printf("%d ",f.bit.b4);
	printf("%d ",f.bit.b3);
	printf("%d ",f.bit.b2);
	printf("%d ",f.bit.b1);

	return 0;
}

処理結果
1 1 1 1 1 1 1 0

■ビット演算も出来ます

#include <stdio.h>

union Field
{
	struct Bit
	{
		unsigned char b1 :1;
		unsigned char b2 :1;
		unsigned char b3 :1;
		unsigned char b4 :1;
		unsigned char b5 :1;
		unsigned char b6 :1;
		unsigned char b7 :1;
		unsigned char b8 :1;
	} bit;
	unsigned char ch;
};


int main(char* argv[])
{
	Field f;
	f.ch =254;

	f.bit.b1 =1;
	printf("%d\n",f.ch);

	return 0;
}

処理結果
255





▲トップページ > Windows と C++