Yktula
Yktula

Reputation: 14809

Operator precedence and struct definition in C

struct struct0 {
  int a;
};

struct struct1 {
  struct struct0 structure0;
  int b;
} rho;


&rho->structure0; /* Reference 1 */
(struct struct0 *)rho; /* Reference 2 */
(struct struct0)rho; /* Reference 3 */
  1. From reference 1, does the compiler take the address of rho, and then access structure0, or vice-versa?

  2. What does the line at reference 2 do?

  3. Since structure0 is the first member of struct1, would reference 3 be equivalent to reference 1?

Upvotes: 0

Views: 890

Answers (2)

Phong
Phong

Reputation: 6768

&rho->structure0; /* Reference 1 */
(struct struct0)rho; /* Reference 3 */
(struct struct0 *)rho; /* Reference 2 */

All the three reference is not right:

  • rho is not a pointer. So you can not do rho->structure0 but (&rho)->structure0
  • You can not convert a variable to a pointer, so you can not do (struct struct0)rho; but (struct struct0 *)&rho

I quite dont really understand what you want to do, so I can not help you much.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224884

In order of your references:

  1. the -> has higher precedence than the &. You're going to get the address of rho->structure0. Or rather, you would if rho were a pointer. Since it's not, you'll get a compile error.
  2. That won't work - you're casting a structure to a pointer type - you should get compiler error doing that.
  3. You can't do that either. A typecast to a non-scalar type is also an error.

Your examples #2 and #3 are covered by the standard section 6.5.4:

Unless the type name specifies a void type, the type name shall specify qualified or unqualified scalar type and the operand shall have scalar type.

If you put any of that code in a compiler you'd see the same results; is the code you're showing not what you intended to ask about?

Upvotes: 4

Related Questions