开发者

What is "protecting a variable" in C? How does it work?

开发者_StackOverflow中文版

In C++, we have the abstraction and data hiding. Can we achieve this through C?


Define your struct in a .C file, and only 'forward declare' the struct in your header.

So your .C file could contain this:

struct Car
   {
   char *brand;
   int   maxspeed;
   };

And your .H file could contain this:

typedef struct Car *CarHandle;

Then write functions to manipulate the Car (setters, getters, ...) and put them in the same .C file as where the struct is defined. Of course, the function prototypes should be put in the header.

Now the callers can use the CarHandle and the functions that operate on the CarHandle, but never see what's inside the Car struct.


You can using incomplete, and derived types, similar to the "opaque data" concept in C++. This is a pretty well written article on the subject.


you can do it with static (global) variables and extern functions to manipulate them.


As Peter Miehle mentionned, you can create variables and functions that are private to a module (often the same as file, I suppose depending on the compiler).

You could compare modules to classes. static variables are only accessible from within the module. You can also have the equivalent to private functions by declaring functions as static within a module.

The difference between this and real classes is that you can have only one instance. But with little work, you can also mimic the implementation of several instances.


The High and Low-Level C article contains a lot of good tips. Especially, take a look at the "Abstract Data Types" section.

See also: What methods are there to modularize C code?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜