routines in structures ?

S

Skybuck Flying

Hello,

Is it possible to declare routines in structures ?

Something like:

struct
{
int a, b, c

void Test;

} myStruct;

void myStruct.Test()
{
a = 5;
}

Only a,b,c would be stored in the structure.

This would allow to associate routines with structures a little bit better,
just syntaxtically.

Instead of writing:

myStruct_Test( myStruct );

I could for example write something like:

myStruct.Test();

Bye,
Skybuck.
 
M

Malcolm McLean

Skybuck Flying said:
Hello,

Is it possible to declare routines in structures ?

Something like:

struct
{
int a, b, c

void Test;

} myStruct;

void myStruct.Test()
{
a = 5;
}

Only a,b,c would be stored in the structure.

This would allow to associate routines with structures a little bit
better, just syntaxtically.

Instead of writing:

myStruct_Test( myStruct );

I could for example write something like:

myStruct.Test();
Probably you want C++.
However use of function pointers can produce something very similar to a C++
struct with function members. However you have to initialise each function
pointer explicitly.
 
B

Ben Bacarisse

Skybuck Flying said:
Is it possible to declare routines in structures ?

Something like:

struct
{
int a, b, c
void Test;
} myStruct;

void myStruct.Test()
{
a = 5;
}
No.

Instead of writing:

myStruct_Test( myStruct );

I could for example write something like:

myStruct.Test();

<OT>
Interestingly, BCPL (a precursor to B and thus, in some way, C) has
some syntax to assist with virtual method calls. The special kind of
function call:

FUNCTION#(E1, E2, ...)

is taken to mean

E1!0!FUNCTION(E1, E2, ...)

which calls the function pointed to by the element numbered FUNCION in
the zeroth element of the E1 vector (a!x is BCPL version of a[x]).

This syntax was probably added after the split with B but it is
interesting to speculate on how the world would have looked if it had
been there before!
</OT>
 
P

Peter 'Shaggy' Haywood

Groovy hepcat Skybuck Flying was jivin' in comp.lang.c on Sun, 10 Feb
2008 7:36 am. It's a cool scene! Dig it.
Is it possible to declare routines in structures ?

If by routines you mean functions, then no. You can, however, declare
pointers to functions in structures. For example:

#include <stdio.h>

struct somestruct
{
void (*somefunc)(void);
};

void thefunc(void)
{
puts("Hello, World!");
}

int main(void)
{
struct somestruct thestruct = {thefunc};
thestruct.somefunc();
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top