C language casting problem

Hi there,

I hope you can help me with a casting problem in C language.

Let's assume TYPE_A and TYPE_B are two types (for example two structure types), and a and b are two variables declared as follows:

TYPE_A a
TYPE_B b

What is the difference between these two casting operations:

1) b = (TYPE_B) a
2) b = * (TYPE_B *) &a

Thank you in advance for your answers.

best regards
absolutely nothing, both of them archieve the same.

1) a is just converted to a TYPE_B
2) the adress of A is converted to a TYPE_B* (pointer) and then dereferenced
are there other opinions?
read below
Last edited on
They are not the same.

1) b = (TYPE_B) a
I don't think you can cast between two different struct types this way in C. If TYPE_A and TYPE_B are fundamental types it works but the result depends on the types involved.

2) b = * (TYPE_B *) &a
&a gives you a pointer to a (TYPE_A*). The pointer is then casted to a TYPE_B* so when the dereference operator * is used it will read a as if it had type TYPE_B.

Here is an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>

typedef struct
{
	short s;
} TYPE_A;

typedef struct
{
	char c1;
	char c2;
} TYPE_B;

int main()
{
	TYPE_A a;
	TYPE_B b;
	
	a.s = 0x0102;
	
	b = * (TYPE_B *) &a;

	printf("%d %d\n", b.c1, b.c2);
}
2 1

The content of a is copied to b exactly how it's stored in memory, but because the two types are different they will be interpreted differently. The short value 0x0102 (258) consists of two bytes with values 1 and 2 (assuming short is 2 bytes) so when c1 and c2 is read from b it gives you value 1 and 2.
Last edited on
So pointer-casting is allways possible without compiler issues?

This seems like it might lead to many problems, can you give me an example where that could be used in a good way?
Yes, casting can lead to problems if you are not careful. I haven't used that much C to know how useful casts like these are, but remember that C has a weaker type system, no inheritance and things like that, and void* is often used as a pointer to any type, so more responsibility on the programmer to know what he's doing.

C-style casts are usually not recommended in C++, but instead we have dynamic_cast, reinterpret_cast, static_cast and const_cast for different purposes.

And to be honest, the example I posted above is probably not a good one. I think it might break the strict aliasing rules, which would make it unsafe to use.

http://en.wikipedia.org/wiki/Aliasing_%28computing%29#Conflicts_with_optimization
Topic archived. No new replies allowed.