Aragorn
Aragorn

Reputation: 353

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

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

Upvotes: 3

Views: 441

Answers (5)

Patrick
Patrick

Reputation: 23619

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.

Upvotes: 6

Judge Maygarden
Judge Maygarden

Reputation: 27593

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?

Upvotes: 0

Gauthier
Gauthier

Reputation: 41965

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.

Upvotes: 0

Alan
Alan

Reputation: 46833

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.

Upvotes: 2

Peter Miehle
Peter Miehle

Reputation: 6070

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

Upvotes: 0

Related Questions