구조체의 호환 규칙

MySprtlty·2022년 8월 5일
0

C

목록 보기
29/37

🏷️구조체의 호환 규칙

  • 이미 선언되어 있는 구조체와 호환(compatible)되도록 하는 규칙이 존재한다.
  • 기본적인 규칙은 다음과 같다.

📌기본적인 규칙

같은 scope다른 scope
같은 tag호환 O호환 X
다른 tag호환 X호환 X

1. 같은 tag & 같은 scope

typedef struct foo foo; /* struct foo is incomplete type.*/

struct foo
{
	/*member declaration*/
};
  • 두 구조체는 compatible type(호환형)이다.
  • 🖇️cf) 첫 typedef 선언에서는 struct foo는 크기가 정해지지 않는 incomplete type(불완전형)이었다가, 멤버 선언을 하는 아래 구조체 선언 이후, composite type(합성형)으로서 complete type(완전형)이 된다.

2. 같은 tag & 다른 scope

struct foo
{
    /*member declaration*/
};

struct foo object1;

{
	struct foo
    {
        /*member declaration*/
    };
    struct foo object2;
    object2 = object1; /* wrong */
}
  • 첫번째 tag 명칭 선언과 두번째 tag 명칭 선언은 호환되지 않는 구조체형을 생성한다.
  • 따라서 두 구조체 object간에 대입 연산이 성립되지 않는다.
  • 다음은 진단 메세지다.

    compiler: GNU GCC Compiler
    error: incompatible types when assigning to type 'struct foo' from type 'struct foo'

3. 다른 tag & 같은 scope

struct foo
{
    /*member declaration*/
};

struct bar
{
      /*member declaration*/
};
  • 당연히 호환되지 않는다.

4. 다른 tag & 다른 scope

struct foo
{
    /*member declaration*/
};

{
    struct bar
    {
        /*member declaration*/
    };
}
  • 마찬가지로 당연히 호환되지 않는다.

📌특별한 규칙

  • 그러나, 예외적인 규칙이 존재한다.

  • 멤버 선언이 없이, 바로 declarator(선언자)가 따르는 형태의 구조체 선언에 적용되는 규칙이다.

  • 🖇️cf) declarator는 명칭(= 식별자, identifier)같은 요소를 포함하는 개념이다.

  • declarator가 따르는 형태의 선언에서

    동일한 tag 명칭이 보임동일한 tag 명칭이 보이지 않음
    호환 Oincomplete type

1. 동일한 tag 명칭이 보임

struct foo
{
  	/*member declaration*/
};

struct foo object; /*멤버 선언 없이, declarator(선언자)가 따르는 형태의 구조체 선언 */
  • 두 구조체형은 호환된다.

2. 동일한 tag 명칭이 보이지 않음

struct foo *object; /*멤버 선언 없이, declarator(선언자)가 따르는 형태의 구조체 선언 */

struct foo
{
	int a;
}
  • struct foo *object;선언에서 foo가 보이지 않는다.
  • 따라서 struct foo는 incomplete type이 된다.
  • 🖇️cf) struct foo *objcet;에서 *object가 declarator에 해당한다.

0개의 댓글