Type cast doesn't work in ternary operator

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Type cast doesn't work in ternary operator

wangwzc
This post was updated on .
The code is as following, when I change the Line14 to (*((struct b_t *)(&dst)) = *((struct b_t *)(&src))) , or I change the Line15 to (*((struct a_t *)(&dst)) = *((struct a_t *)(&src))), it's OK. Quite strange, why two kind of type cast doesn't work.

# gcc a.c
a.c: In function `main':
a.c:15: error: type mismatch in conditional expression

========== a.c =============
struct a_t {
        int sa_family;
};

struct b_t {
        int sa_family;
};

int main()
{
        struct b_t dst, src;

        (src.sa_family == 1) ?
        (*((struct a_t *)(&dst)) = *((struct a_t *)(&src))) : // Line14
        (*((struct b_t *)(&dst)) = *((struct b_t *)(&src)));      // Line 15

        return 0;
}
Reply | Threaded
Open this post in threaded view
|

Re: Type cast doesn't work in ternary operator

Vincent Lefevre-3
On 2015-03-02 01:16:40 -0700, wangwzc wrote:
> The code is as following, when I change the Line15 to (*((struct b_t
> *)(&dst)) = *((struct b_t *)(&src))) , or I change the Line16 to (*((struct
> a_t *)(&dst)) = *((struct a_t *)(&src))), it's OK. Quite strange, why two
> kind of type cast doesn't work.

Line 16 is already (*((struct a_t *)(&dst)) = *((struct a_t *)(&src))).

> # gcc a.c
> a.c: In function `main':
> a.c:15: error: type mismatch in conditional expression
>
> ========== a.c =============
> struct a_t {
> int sa_family;
> };
>
> struct b_t {
> int sa_family;
> };
>
> int main()
> {
> struct b_t dst, src;
>
> (src.sa_family == 1) ?
> (*((struct a_t *)(&dst)) = *((struct a_t *)(&src))) :
> (*((struct a_t *)(&dst)) = *((struct a_t *)(&src)));
>
> return 0;
> }

No problems with GCC 4.9.2.

Note that struct a_t and struct b_t are not compatible, even though
they look the same.

--
Vincent Lefèvre <[hidden email]> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)