On Tue, Sep 16, 2008 at 9:57 AM, Sean McBride <[EMAIL PROTECTED]> wrote:
> On 9/16/08 9:45 AM, Clark Cox said:
>
>>> NSPoint and CGPoint may be the same now, but they may not always be.
>>> (Consider that NSAffineTransformStruct and vImage_AffineTransform were
>>> the same, but the former changed from float to CGFloat and the latter
>>> stayed float, even in 64 bit.)
>>>
>>> Also, they are separate structs to the compiler, so it is free (though
>>> unlikely) to align and pack them differently.
>>
>>No, it is not. The C standard guarantees that two structs with the
>>same initial sequence of members have the same layout as far as the
>>common members are concerned. The following is perfectly legal code:
>>
>>#include <stdio.h>
>>
>>typedef struct Foo { float x, y; } Foo;
>>typedef struct Bar { float x, y; } Bar;
>>
>>int main() {
>>  Foo f = {123,456};
>>
>>  //Treat f as if it is a Bar:
>>  printf("x = %f\n", ((Bar*)&f)->x);
>>  printf("y = %f\n", ((Bar*)&f)->y);
>>
>>  return 0;
>>}
>
> Well, I am certainly no language lawyer.  Perhaps I am confusing
> things.  I am thinking of gcc's "warning: dereferencing type-punned
> pointer will break strict-aliasing rules".  For example, compile your
> snippit above like so:
>
> $ gcc-4.2 -Wall -Wextra -fstrict-aliasing test.m
> test.m: In function 'main':
> test.m:10: warning: dereferencing type-punned pointer will break strict-
> aliasing rules
> test.m:11: warning: dereferencing type-punned pointer will break strict-
> aliasing rules
>
> This is what I was remembering:
> <http://www.cellperformance.com/mike_acton/2006/06/
> understanding_strict_aliasing.html#introduction>

OK, examples that don't involve type-punned pointers:
#include <stdio.h>

typedef struct Foo { float x, y; } Foo;
typedef struct Bar { float x, y; } Bar;

int main() {
        union {
                Foo f;
                Bar b;
        } u;
        
        u.f.x = 123;
        u.f.y = 456;
        
        printf("x = %f\n", u.b.x);
        printf("y = %f\n", u.b.y);

        return 0;
}

Or:

#include <stdio.h>

typedef struct Foo { float x, y; } Foo;
typedef struct Bar { float x, y; } Bar;

int main() {
        Foo f = {123,456};
        Bar b;
        
        memcpy(&b, &f, sizeof f);
        
        printf("x = %f\n", b.x);
        printf("y = %f\n", b.y);

        return 0;
}

-- 
Clark S. Cox III
[EMAIL PROTECTED]
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to