【C】Pointer (11) You Can Define Same Tag Name at Most Once

※ 日本語ページはこちら

Where two declarations that use the same tag declare the same type, they shall both use the same choice of struct, union, or enum.

As far as I confirm by writing codes, in the end, I think I can declare same tag name only at once.

Here is the code. Using same tag name in union and structure. This will be error. uniton-structure.c

#include <stdio.h>

int main (void ){
	union test {
		char c;
		int i;
	} test1;  	
	
	struct test {
		char c;
		int i;
	} test1;  	

	test1.c = "A";

	printf("test1.c = %c \n", test1.c);
	printf("test1.i = %i \n", test1.i);

	test1.i = 100 ;

	printf("test1.c = %c \n", test1.c);
	printf("test1.i = %i \n", test1.i);

	return 0;
}

Compile result of union-structure.c

$ gcc union_structure.c 
union_structure.c: In function ‘main’:
union_structure.c:10:9: error: ‘test’ defined as wrong kind of tag
  struct test {
         ^
union_structure.c:13:4: error: conflicting types for ‘test1’
  } test1;   
    ^
union_structure.c:8:4: note: previous declaration of ‘test1’ was here
  } test1;   
    ^
union_structure.c:15:10: warning: assignment makes integer from pointer without a cast [enabled by default]
  test1.c = "A";
          ^

Different tag name for union and structure union_structure2.c

#include <stdio.h>

int main (void ){
        struct test2 {
                char c;
                int i;
        } st;

        union test1 {
                char c;
                int i;
        } uni;

        st.c = 'A';
        uni.c = 'A';
        st.i = 100 ;
        uni.i = 100 ;

        printf("st.c = %d \n", st.c);
        printf("st.i = %d \n", st.i);
        printf("uni.c = %d \n", uni.c);
        printf("uni.i = %d \n", uni.i);

        st.i = 260 ;
        uni.i = 260 ;
        printf("st.c = %d \n", st.c);
        printf("st.i = %d \n", st.i);
        printf("uni.c = %d \n", uni.c);
        printf("uni.i = %d \n", uni.i);

        return 0;
}

Compile result and execution result of union_structure2.c

$ gcc union_structure2.c 
$ ./a.out 
st.c = 65 
st.i = 100 
uni.c = 100 
uni.i = 100 
st.c = 65 
st.i = 260 
uni.c = 4 
uni.i = 260 

That’s all for this time.

!!! All copyrights belong to the writer of this contents.