Liste des Groupes | Revenir à cl c |
On 08/04/2025 18:32, Tim Rentsch wrote:Of course. They are different types.bart <bc@freeuk.com> writes:I get an incompatible error (from the example you snipped) even when I remove both struct tags.
>On 08/04/2025 15:50, David Brown wrote:>
>On 08/04/2025 13:35, bart wrote:>
>But this need not be the case. For example this is module A:>
>
--------------------------
#include <stdio.h>
>
typedef struct point {float a; float b;} Point;
>
float dist(Point);
>
int main(void) {
Point p = {3, 4};
printf("%f\n", dist(p));
}
--------------------------
>
And this is module B that defines 'dist':
>
>
--------------------------
#include <math.h>
>
typedef float length;
typedef struct _tag {length x, y;} vector;
>
length dist(vector p) {return sqrt(p.x*p.x + p.y*p.y);}
--------------------------
>
The types involved are somewhat different, but are compatible
enough for it to work.
The two types are entirely compatible.
Are they?
No, they are not. The type names 'Point' and 'vector' name two
distinct types, and those types are not compatible, because
the two struct tags are different.
>
Because the two types are not compatible, even just calling the
function dist() is undefined behavior.
I can't use the same struct tag in the same scope as one will clash with the other.Yes.
But if I have the second in an inner scope, then I again get the error.Yes.
It doesn't seem to be anything to do with struct tags.Correct.
Two typedefs for same struct layout appear to create distinct types; this fails:"typedef" does not create types - it merely creates an alias for an existing type. (Is it a questionable choice of keyword? Yes, it certainly is. So you have to learn what it means.) "struct" declarations (and "union" declarations) create types.
typedef struct {float x, y;} Point;This creates a new anonymous type, then declares "Point" to be an alias for it.
typedef struct {float x, y;} vector;This creates a new anonymous type, then declares "vector" to be an alias for it.
Point p;This creates a new anonymous type, then declares "Point" and "vector" to be aliases of it. They therefore refer to the same type.
vector v;
p=v;
But this works:
typedef struct {float x, y;} Point, vector;
Point p;It depends on whether they are declared as aliases for the same type, or for different types.
vector v;
p=v;
So it seems to depend on whether Point and vector share the same internal descriptor for the struct.
In my original example, the structs were defined in separate translation unit, so the compiler has to take things on trust.Yes - as explained in 6.2.7p1 of the standard. Having them in separate translation units is critical to the difference.
Les messages affichés proviennent d'usenet.