Alex Rivera | Logout

How can I hide the declaration of a struct in C?

Asked 2009-07-20T17:02:07.530
13

In the question Why should we typedef a struct so often in C?, unwind answered that:

In this latter case, you cannot return the Point by value, since its declaration is hidden from users of the header file. This is a technique used widely in GTK+, for instance.

How is declaration hiding accomplished? Why can't I return the Point by value?

ADD:

I understood why I can't return the struct by value, but, is still hard to see why i can't deference this point in my function. i.e. If my struct have member named y, why i can't do it?

 pointer_to_struct->y = some_value; 

Why should I use methods to do it? (Like Gtk+)

Thanks guys, and sorry for my bad english again.

c
Edit
Report

1 Answer

5

In the header file:

typedef struct _point * Point;

After the compiler sees this it knows:

  • There is a struct called _point.
  • There is a pointer type Point that can refer to a struct _point.

The compiler does not know:

  • What the struct _point looks like.
  • What members struct _point contains.
  • How big struct _point is.

Not only does the compiler not know it - we as programmers don't know it either. This means we can't write code that depends on those properties of struct _point, which means that our code may be more portable.

Given the above code, you can write functions like:

Point f() {
   ....
}

because Point is a pointer and struct pointers are all the same size and the compiler doesn't need to know anything else about them. But you can't write a function that returns by value:

struct _point f() {
  ....
}

because the compiler does not know anything about struct _point, specifically its size, which it needs in order to construct the return value.

Thus, we can only refer to struct _point via the Point type, which is really a pointer. This is why Standard C has types like FILE, which can only be accessed via a pointer - you can't create a FILE structure instance in your code.

answered 2009-07-20T17:12:52.907

Your Answer