0
//data type 1
typedef struct t_A{
    int mJ;
}A;

//data type 2        
typedef struct t_B{
    int mK;
}B;

//Function returning B object which is a rValue
B funcRetB(void)
{
    B test;
    test.mK = 9;
    return test;
}

void main(void)
{
    A a;
    a = (A)funcRetB(); //How to typecast this without defining a variable of B?
}

The above code gives error "error C2440: 'type cast' : cannot convert from 'B' to 'A'". Is it possible to resolve this error in C?

1 Answers1

0

I believe, but couldn't quickly find it in the standard, that typedef introduces a new type that is only compatible with itself.

Although A and B are defined the same, the compiler will treat them as different types. When the function returns a complete object of type B, the compiler now does not know how to copy that to an object of type A. Because you copy objects, the cast won't work because, as far as the compiler is concerned, all members may be differently laid out so the compiler doesn't know how to copy the objects to one another.

See the links provided in the comments for tips and tricks.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41