Huzo
Huzo

Reputation: 1692

Pointer of a union

Consider the union type below.

typedef union nodeTypeTag {
    nodeEnum nodeType; 
    ruleNode rule; 
    conNode cond; 
    actNode act; 
    exprNode expr; 
    litNode lit; 
} ASTnode;

in which nodeEnum is enum and ruleNode, conNode, actNode, exprNode, litNode are all structure types.

Now, assume that in my main function, I do this:

ASTnode * tmp;
tmp = (ASTnode *) malloc(sizeof(ASTnode)); 

and assume that I have another function which takes parameters:
myfun(conNode * conditions) What would happen if I pass tmp to this function? Would it give error? Why? Would it do implicitly change type of pointer? I am new to the idea of union types.

Thanks

Upvotes: 2

Views: 71

Answers (1)

P.W
P.W

Reputation: 26800

The pointer to ASTnode (which is union nodeTypeTag *) and the pointer to conNode (struct *) are incompatible. And it is definitely wrong to pass one in stead of the other.

The standard only says that (C11 6.2.5 28):

All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

But pointers to union types and pointers to structure types do not have the same representation and alignment requirements.

Also relevant here is 6.5.7

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,

Attempt to access the object of type conNode through a non-compatible type in myfun is a violation of the above rule.

Upvotes: 2

Related Questions