473,785 Members | 2,830 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Adding the ability to add functions into structures?

So structures are useful to group variables, so you can to refer to a
collection as a single entity. Wouldn't it be useful to also have the
ability to collect variable and functions?

Ask K&R say, C programs consist of variables to store the input and
functions to manipulate them.

This would make C object-oriented - how cool would that be?

Are there any problems with adding the ability to have functions
encapsulated in structures?

Dec 31 '05
47 3896
On Sat, 31 Dec 2005 05:54:27 +0000 (UTC), Richard Heathfield
<in*****@invali d.invalid> wrote in comp.lang.c:
Jack Klein said:
I know I'll get flamed for this,
FLAME ON!!!
but with the exception of inheritance
this is really nothing but syntactical sugar. You can write object
oriented programs in C right now.


Oh. Was that it? Sheesh. Flame off again. (sigh)
A perfect example is the FILE data type, declared an <stdio.h>. It
has a creator, fopen(), a destructor, fclose(), and all sorts of
methods you can invoke on it via its pointer, such as fprintf(),
fscanf(), fread(), fwrite(), between its successful creation and its
destruction.


This is pretty much how I do it, yes. Just a minor nit - FILE isn't (quite)
a perfect example, in at least two ways:

1) FILE should, in my opinion, be a truly opaque type, with the structure
definition hidden internally. typedef struct _iobuf FILE; is already more
than we need to know. The whole schmeer is far, far more than we need to
know.


I agree that FILE is not a perfectly opaque type, although I
deliberately decided not to complicate the point I was making to the
OP by bringing that up.

FILE cannot truly be an opaque type as far standard C is concerned for
the simple reason that the standard requires some functions to be
implemented as macros, and so some of the details must be exposed by
<stdio.h>.

Nevertheless, it is opaque enough for the point of the article, in the
sense that none of its internal details or workings are documented.
There is nothing that a strictly conforming program can do with a FILE
* other than through the documented functions.
2) I wish I wish I wish that fclose took FILE ** rather than FILE *, don't
you?


The one I consider much more important than that would be defining
fclose(NULL) as a no-op, just like free(NULL) is. It would greatly
simplify cleaning up resources. Right now you have to write code like
this:

WARNING: pseudo code not compiled, tested, or sanity checked!

return_type some_func( /*...*/)
{
FILE *fin = NULL;
FILE *fout = NULL;
data_type *data_ptr = NULL;
return_type something = DEFAULT_VALUE;

/* ... */

fin = fopen(...);
fout = fopen(...);
data_ptr = malloc(...);

/* ... */

if (fin) fclose(fin);
if (fout) fclose(fout);
free(data_type) ;

return something;
}

The additional checking for null FILE pointers before calling fclose()
is not a major effort, but it is just annoying enough to earn a place
on the pet peeve list after writing it INT_MAX times.

BTW, what's wrong with:

void rh_fclose(FILE **fp)
{
if (*fp)
{
fclose(*fp);
*fp = NULL;
}
}

Of course, I could just as easily write:

void jk_fclose(FILE *fp)
{
if (fp) fclose(fp);
}

Maybe time for both of us to make a new year's resolution to stop
carping about the easily fixable stuff?

Nah, that would take all the fun out of it!

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Dec 31 '05 #21
On Sat, 31 Dec 2005 12:23:31 +0000 (UTC), "Malcolm"
<re*******@btin ternet.com> wrote in comp.lang.c:

"Jack Klein" <ja*******@spam cop.net> wrote
I know I'll get flamed for this, but with the exception of inheritance ^^^^^^^^^^^^^^^ ^^^^^^^^^
this is really nothing but syntactical sugar. You can write object
oriented programs in C right now.

A perfect example is the FILE data type, declared an <stdio.h>. It
has a creator, fopen(), a destructor, fclose(), and all sorts of
methods you can invoke on it via its pointer, such as fprintf(),
fscanf(), fread(), fwrite(), between its successful creation and its
destruction.

Inheritance is crucial.


Says who? The first hit on Google for the phrase "object oriented"
including quotations is
http://java.sun.com/docs/books/tutorial/java/concepts/, which has the
page title "Object-Oriented Programming Concepts". The first question
and answer on this page are:

What Is an Object?

An object is a software bundle of related variables and methods.
Software objects are often used to model real-world objects you find
in everyday life.

Further down the page comes the question "What is Inheritance".

Inheritance is a heavily-used feature that is provided by most object
oriented languages and systems, but it is indeed an extra feature. The
true definition of object orientation is pretty well captured in the
first question and answer. Object orientation means that data is
encapsulated and not manipulated directly, only via specifically
defined functions, often called "methods." And the C FILE type meets
this definition.
An object is any set of data items that are "part of the same thing". C
structures are therefore objects. (The C standard further specifies that an
object must be stored contigously in memory. This is a language issue and a
fairly obvious thing to do, but not strictly necessary).
That's quite correct. In actual fact, the definition of "object" in
the C++ language standard is exactly the same as it is in C, and has
nothing at all to do with classes or object oriented programming. In
C++, as in C, an int is an object.
A program becomes "object-oriented" not when it uses objects, but when the ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
This is an interesting point of view, and one perhaps subscribed to by
many programmers who use object oriented paradigms, perhaps in
languages that have more built-in support for it than C does. Still,
I would be mildly surprised if you could find an authoritative
definition of "object orientation" that states that inheritance is
required.
objects enter into relationships with each other. In C++ like most lanauges
that support obect-orientation, this is achieved via inheirtance. However
there are other ways, for example Microsoft Windows objects all respond to
the same message system, Java interfaces specify common methods, text
adventure objects have verb handlers.


Actually, inheritance can be done in C as well, but the result tends
to be rather messy. Most people who attempt it are trying to write
C++ in C and, in my experience, the result is neither good C++ nor
good C.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Dec 31 '05 #22
Jack Klein wrote:
[...]
FILE cannot truly be an opaque type as far standard C is concerned for
the simple reason that the standard requires some functions to be
implemented as macros, and so some of the details must be exposed by
<stdio.h>.


What functions that deal with FILE or FILE* are required
to be macros?

--
Eric Sosman
es*****@acm-dot-org.invalid
Dec 31 '05 #23
On Sat, 31 Dec 2005 16:29:02 -0500, in comp.lang.c , Eric Sosman
<es*****@acm-dot-org.invalid> wrote:
Jack Klein wrote:
[...]
FILE cannot truly be an opaque type as far standard C is concerned for
the simple reason that the standard requires some functions to be
implemented as macros, and so some of the details must be exposed by
<stdio.h>.


What functions that deal with FILE or FILE* are required
to be macros?


getchar() and getc() may be implemented as a macro, as may the put...
equivalents.
..
Mark McIntyre
--

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Jan 1 '06 #24
Mark McIntyre <ma**********@s pamcop.net> writes:
On Sat, 31 Dec 2005 16:29:02 -0500, in comp.lang.c , Eric Sosman
<es*****@acm-dot-org.invalid> wrote:
Jack Klein wrote:
[...]
FILE cannot truly be an opaque type as far standard C is concerned for
the simple reason that the standard requires some functions to be
implemented as macros, and so some of the details must be exposed by
<stdio.h>.


What functions that deal with FILE or FILE* are required
to be macros?


getchar() and getc() may be implemented as a macro, as may the put...
equivalents.


Any library function may be implemented as a macro. I think assert()
is the only one that's required to be a macro.

getc() and putc() are equivalent to fgetc() and fputc(), respectively,
except that *if* they're implemented as macros they can evaluate their
stream arguments more than once.

A conforming implementation could make getc() and putc() regular
functions without macro equivalents, and make FILE as opaque as it
likes (it still has to be an object type), but making them macros is
probably important for performance.

Then again, FILE could be just an array of N unsigned chars (or a
struct containing such an array), with the code that uses it
converting FILE* to REAL_FILE* to access the internals.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 1 '06 #25
Jack Klein said:
FILE cannot truly be an opaque type as far standard C is concerned for
the simple reason that the standard requires some functions to be
implemented as macros, and so some of the details must be exposed by
<stdio.h>.
Absolutely true, but a nuisance nonetheless.
2) I wish I wish I wish that fclose took FILE ** rather than FILE *,
don't you?


The one I consider much more important than that would be defining
fclose(NULL) as a no-op, just like free(NULL) is.


That, too.

The additional checking for null FILE pointers before calling fclose()
is not a major effort, but it is just annoying enough to earn a place
on the pet peeve list after writing it INT_MAX times.
For sufficiently low values of INT_MAX, anyway.
BTW, what's wrong with:

void rh_fclose(FILE **fp)
{
if (*fp)
{
fclose(*fp);
*fp = NULL;
}
}


Nothing. That's how most of my opaque type destructors look. But (and this
will perhaps raise a chuckle) whilst I freely and consciously borrowed the
FILE * model for my opaque types - with the above modification - it had not
actually occurred to me to wrap C's I/O streams in this model! Thanks for
the suggestion. :-)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 1 '06 #26
Keith Thompson wrote:
Mark McIntyre <ma**********@s pamcop.net> writes:
On Sat, 31 Dec 2005 16:29:02 -0500, in comp.lang.c , Eric Sosman
<es*****@ac m-dot-org.invalid> wrote:
Jack Klein wrote:

[...]
FILE cannot truly be an opaque type as far standard C is concerned for
the simple reason that the standard requires some functions to be
implement ed as macros, and so some of the details must be exposed by
<stdio.h> .

What functions that deal with FILE or FILE* are required
to be macros?


getchar() and getc() may be implemented as a macro, as may the put...
equivalents .

Any library function may be implemented as a macro. I think assert()
is the only one that's required to be a macro.


There's also setjmp().

However, that wasn't what I asked. Jack Klein wrote that
the Standard *requires* some functions to be implemented as
macros, and this is true. However, I was unable to think of
any FILE-using functions that are *required* to be macros. Can
you suggest any such?

I'm well aware that the Standard *permits* an implementation
to provide macros for any library functions it chooses, so long
as it provides the actual function as well. I'm also aware that
the Standard makes special provision for getc() and putc() (but
not for getchar(), by the way) that make macro implementations
easier. But does the Standard *require* a macro implementation
for any FILE or FILE* function?

... and what this all comes down to, of course, is whether
FILE can be a fully opaque type. I believe it can be, but both
Jack Klein and Richard Heathfield (two not-to-be-ignored people)
take the opposite view. I'm trying to learn why.

--
Eric Sosman
es*****@acm-dot-org.invalid
Jan 1 '06 #27
Eric Sosman said:
I'm well aware that the Standard *permits* an implementation
to provide macros for any library functions it chooses, so long
as it provides the actual function as well. I'm also aware that
the Standard makes special provision for getc() and putc() (but
not for getchar(), by the way) that make macro implementations
easier. But does the Standard *require* a macro implementation
for any FILE or FILE* function?

... and what this all comes down to, of course, is whether
FILE can be a fully opaque type. I believe it can be, but both
Jack Klein and Richard Heathfield (two not-to-be-ignored people)
take the opposite view. I'm trying to learn why.


Well, to be perfectly honest with you I was just nodding "wisely" at Jack's
assertion rather than think it through myself. (So much for
not-to-be-ignored!)

But now that I'm actually thinking about it (albeit not terribly brightly,
since dinner is moderately imminent), I don't know of anything that would
stop the following program from being strictly conforming:

#include <stdio.h>

int main(void)
{
FILE foo;
return 0;
}

and of course that wouldn't be legal if FILE were truly opaque.

Also, I was half-thinking (er, yes, I think that's what I mean) of the
possibility that, since getc et al *can* be implemented as macros, it is
necessary to make FILE visible in order to allow implementors the freedom
to implement it as a macro if they so choose. This is probably what Jack
meant, although even now I will freely admit that I haven't thought this
through thoroughly, or at least I don't think I have.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 1 '06 #28
Jack Klein wrote:
.... snip wishes from RH about fclose(FILE**) ...
The additional checking for null FILE pointers before calling
fclose() is not a major effort, but it is just annoying enough
to earn a place on the pet peeve list after writing it INT_MAX
times.> BTW, what's wrong with:

void rh_fclose(FILE **fp)
{
if (*fp)
{
fclose(*fp);
*fp = NULL;
}
}


If this is called from a function that can be passed a generic
FILE*, that may actually be stdin or stdout. I don't believe the
standard insists on those being modifiable pointers.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Jan 1 '06 #29
Albert a écrit :
So structures are useful to group variables, so you can to refer to a
collection as a single entity. Wouldn't it be useful to also have the
ability to collect variable and functions?

Ask K&R say, C programs consist of variables to store the input and
functions to manipulate them.

This would make C object-oriented - how cool would that be?

Are there any problems with adding the ability to have functions
encapsulated in structures?


There is no good reason to do that (multipliying function instances ?
Why in the world ?).

The idea behind OOP is that the code is organized around objects and
methods (functions) to manipulate the objects. The objects are designed
to be instanciable, but not the functions. The idea is to have a langage
trick that 'connects' the object and its method:

obj.method()

as in C++, but behind the scene, the method stays unique. What you can
do in C is to store the address of the method (function) in the
structure using a pointer to a function, but it brings nothing really
interesting.

The C-way is rather to define function names like:

type_function()

and to pass the address of the object as the first parameter of these
functions

type_function(t ype *self)

It's also common to have explicit constructors and destructors:

type * type_create()
type_delete(typ e *self)

Note that if you are only using pointers to the objects, the type can be
completely opaque:

typedef struct type type;

A good standard-C-example is the FILE function family.

Constructors / destructors:
fopen() / fclose()

Methods:
fgetc() / fputc() / ferror() etc.

--
A+

Emmanuel Delahaye
Jan 1 '06 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
741
by: Bob Rock | last post by:
Hello, in the last few days I've made my first few attempts at creating mixed C++ managed-unmanaged assemblies and looking aftwerwards with ILDASM at what is visible in those assemblies from a managed point-of-view I've noticed that: 1) for each managed and unmanaged C function (not C++ classes) I get a public managed static method (defined on a 'Global Functions' class) in the generated assembly with an export name of the form...
5
28675
by: Angel | last post by:
Is there some way to add a C-header file into a C# project? The problem is that this .h file contains several complex structures (over 20) that are used by some unmanaged code. These functions receive these defined structs as parms and modify them during execution. Basically, it'd be something siomple like this (but in C#): #include <parms.h> W32_PARM parm;
11
2583
by: ruffiano | last post by:
A colleague of mine who is a C developer wrote several functions in C which I now need to invoke in my C++ application. This is normally not a problem except that the header file that he wrote contains also several structures and #defines, which I need to use in my C++ application. What is the best way to use the C functions, structures and defines in my code without upsetting the compiler / linker? For the C functions I know I need...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10093
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9952
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8976
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3654
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2880
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.