0

NOTE: this is NOT a C++ question, i can't use a C++ compiler, only a C99.

Is this valid(and acceptable, beautiful) code?

typedef struct sA{
   int a;
} A;

typedef struct aB{
   struct sA a;
   int b;
} B;

A aaa;
B bbb;

void init(){
   bbb.b=10;
   bbb.a.a=20;
   set((A*)&bbb);
}

void set(A* a){
   aaa=*a;
}

void useLikeB(){
   printf("B.b = %d", ((B*)&aaa)->b);
}

In short, is valid to cast a "sub class" to "super class" and after recast "super class" to "sub class" when i need specified behavior of it?

Thanks

4
  • 3
    Please note, that if you want to express something similar to inheritance there, you need struct aB to include a struct sA by value and not by pointer i.e. should be struct sA a; Aug 18, 2012 at 13:35
  • Yes sure, i write this quickly, correct.
    – blow
    Aug 18, 2012 at 13:38
  • 1
    Type punning in this manner is a common technique in C; as long as you're careful about what you're doing (and explicitly included the punned type inside the extended type is a good practice!), then you should be able to make good use of it.
    – tbert
    Aug 18, 2012 at 14:01
  • 1
    You are mixing pointers and structs in this code, effectively making it an invalid code (and yes, it doesn't compile). Please fix the code first, and then I can tell you whether you are doing something which is allowed or not. Aug 18, 2012 at 14:27

4 Answers 4

6

First of all, the C99 standard permits you to cast any struct pointer to a pointer to its first member, and the other way (6.7.2.1 Structure and union specifiers):

13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

In other way, in your code you are free to:

  1. Convert B* to A* — and it will always work correctly,
  2. Convert A* to B* — but if it doesn't actually point to B, you're going to get random failures accessing further members,
  3. Assign the structure pointed through A* to A — but if the pointer was converted from B*, only the common members will be assigned and the remaining members of B will be ignored,
  4. Assign the structure pointed through B* to A — but you have to convert the pointer first, and note (3).

So, your example is almost correct. But useLikeB() won't work correctly since aaa is a struct of type A which you assigned like stated in point (4). This has two results:

  1. The non-common B members won't be actually copied to aaa (as stated in (3)),
  2. Your program will fail randomly trying to access A like B which it isn't (you're accessing a member which is not there, as stated in (2)).

To explain that in a more practical way, when you declare A compiler reserves the amount of memory necessary to hold all members of A. B has more members, and thus requires more memory. As A is a regular variable, it can't change its size during run-time and thus can't hold the remaining members of B.


And as a note, by (1) you can practically take a pointer to the member instead of converting the pointer which is nicer, and it will allow you to access any member, not only the first one. But note that in this case, the opposite won't work anymore!

2

I think this is quite dirty and relatively hazardous. What are you trying to achieve with this? also there is no guarantee that aaa is a B , it might also be an A. so when someone calls "uselikeB" it might fail. Also depending on architecture "int a" and "pointer to struct a" might either overlap correctly or not and might result in interesting stuff happening when you assign to "int a" and then access "struct a"

0

Why would you do this? Having

set((A*)&bbb);

is not easier to write than the correct

set(&bbb.a);

Other things that you should please avoid when you post here:

  • you use set before it is declared
  • aaa=a should be aaa = *a
0

First of all, I agree with most concerns from previous posters about the safety of this assignments.

With that said, if you need to go that route, I'd add one level of indirection and some type-safety checkers.

static const int struct_a_id = 1;
static const int struct_b_id = 2;
struct MyStructPtr {
   int type;
   union {
     A* ptra;
     B* ptrb;
     //continue if you have more types.
   }
};

The idea is that you manage your pointers by passing them through a struct that contains some "type" information. You can build a tree of classes on the side that describe your class tree (note that given the restrictions for safely casting, this CAN be represented using a tree) and be able to answer questions to ensure you are correctly casting structures up and down. So your "useLikeB" function could be written like this.

MyStructPtr the_ptr;
void init_ptr(A* pa)
{
     the_ptr.type = struct_a_id 
     the_ptr.ptra = pa;
}
void useLikeB(){
    //This function should FAIL IF aaa CANT BE SAFELY CASTED TO B
    //by checking in your type tree that the a type is below the 
    //a type (not necesarily a direct children).
    assert( is_castable_to(the_ptr.type,struct_b_id ) ); 
    printf("B.b = %d", the_ptr.ptrb->b);
}

My 2 cents.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.