Portability issues in C struct / union

Suppose I have the following type from an external library:

union foreign_t {
    struct {
        enum enum_t an_enum;
        int an_int;
    } header;
    struct {
        double x, y;
    } point;
};

Is it possible to assume that the following code fragment will work as expected on different platforms and with different compilers?

struct pair_t {
    double x, y;
};

union foreign_t foreign;
struct pair_t *p_pair;

p_pair = (struct pair_t *) &foreign;
p_pair->x = 1234;
p_pair->y = 4321;

/* Expected result: (1234, 4321) or something like that */
printf("(%lf, %lf)", foreign.point.x, foreign.point.y);

EDIT:

Following the strictest smoothing suggestion, I did the following test:

#include <stdint.h>
#include <stdio.h>

int main()
{
    uint16_t word = 0xabcd;
    uint8_t tmp;
    struct {
        uint8_t low;
        uint8_t high;
    } *byte = (void *) &word;

    tmp = byte->low;
    byte->low = byte->high;
    byte->high = tmp;

    printf("%x\n", word);

    return 0;
}

The above apparently innocent piece of code is not reliable:

$ gcc -O3 -fno-strict-aliasing -otest test.c
$ ./test
cdab
$ gcc -O3 -fstrict-aliasing -otest test.c
$ ./test
abcd

There is no rest for developers ...

+3
source share
8 answers

, , . , strict aliasing. , , , .

, , , , foreign_t. , , , , . , , , .

+6

, . , foreign , , header.

( header, point , . , .)

+2

, . ANSI C , "" , - , . - , . , , .

+2

, . , foreign.header, foreign.point, .

+1

, , .

+1

, , , , .

foreign union struct, , .

, foreign A B . , , , , IEEE .

, , , / , .

, struct union . , MPEG, .

+1

, double, int enum ( , , double IEEE), . int enum, , .

0

, ?

...

, ,

-1

Source: https://habr.com/ru/post/1720235/


All Articles