Are 'private' or 'public' keywords in ANSI C (or any other C for that matter), or were they only added in C++ (and Java, C#, ...)?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
static isn't like private, given that you can't read a static variable even in the constructor of the class (the function which inits members of a struct in C language).
You only can use static variables in the part of the code where they were defined (in a function, a struct, ...).
private
is not a C89 or C99 keyword. See C Programming/Reference Tables on Wikibooks*.Also, C has nothing** to do with Java and C# (and, really, not C++ either). However, the converse is not true -- C++ grew from C, for example.
* Better reference needed!
** Actually, C89 "borrowed" the
const
andvolatile
keywords from C++. Likewise, C99 "borrowed" theinline
keyword, and also added_Bool
and_Complex
(like C++'sbool
andcomplex
, respectively) [citation-needed].After some thinking i realized that you can just create your own private keyword in c which, like opaque pointers can hide the struct members from the client using an api. So here is a code sample:
api.h
api.c
main.c
using this concept we can also implement a read-only access specifier:
There is only one thing to keep in mind, you can use the Api struct on the Stack. At least not client side. I hope this helps someone.
Neither are C keywords, but some people do the following:
Update:
For those who think it is a bad idea to do the above, I would agree. But it does explain why someone might think
public
orprivate
are C keywords.For those who think it won't compile in C, try this:
For those who think it won't compile in C++, yes the above program will.
Update:
Well actually it is undefined behaviour due to this part of the C++ standard:
So the example above and below are not required to do anything sane in C++, which is a good thing. My answer still is completely valid for C (until it is proven to be wrong! :-) ).
In the case of a C++ class with private members, you can do something similar (considered an abuse) like this:
main.c:
message.hpp: