Functions in structure

23,695

Solution 1

No, but they can contain function pointers.

If your intent is to do some form of polymorphism in C then yes, it can be done:

typedef struct {
    int (*open)(void *self, char *fspec);
    int (*close)(void *self);
    int (*read)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);
    int (*write)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);
    // And data goes here.
} tCommClass;

The typedef above was for a structure I created for a general purpose communications library. In order to initialise the variable, you would:

tCommClass *makeCommTcp (void) {
    tCommClass *comm = malloc (sizeof (tCommClass));
    if (comm != NULL) {
        comm->open  = &tcpOpen;
        comm->close = &tcpOpen;
        comm->read  = &tcpOpen;
        comm->write = &tcpWrite;
    }
    return comm;
}

tCommClass *makeCommSna (void) {
    tCommClass *comm = malloc (sizeof (tCommClass));
    if (comm != NULL) {
        comm->open  = &snaOpen;
        comm->close = &snaOpen;
        comm->read  = &snaOpen;
        comm->write = &snaWrite;
    }
    return comm;
}

tCommClass *commTcp = makeCommTcp();
tCommClass *commSna = makeCommSna();

Then, to call the functions, something like:

// Pass commTcp as first params so we have a self/this variable
//   for accessing other functions and data area of object.
int stat = (commTcp->open)(commTcp, "bigiron.box.com:5000");

In this way, a single type could be used for TCP, SNA, RS232 or even carrier pidgeons, with exactly the same interface.

Solution 2

edit Cleared up ambiguity with the use of 'data types'

Not in C. struct types can only contain data.

From Section 6.7.2.1 of the ISO C99 Standard.

A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.

Solution 3

No, you cannot. A structure cannot contain a declaration of a function but they can contain a definition of a function. A structure can only contain data types, pointers, pointers to different function. You can make a pointer to a function and then access from the structure.

#include<iostream>
#include<cstring>
using namespace std;

struct full_name
{
  char *fname;
  char *lname;
  void (*show)(char *,char*);
};

void show(char *a1,char * a2)
{
  cout<<a1<<"-"<<a2<<endl;
}

int main()
{  
  struct full_name loki;
  loki.fname="Mohit";
  loki.lname="Dabas";
  loki.show=show;
  loki.show(loki.fname,loki.lname);

  return 0;     
}
Share:
23,695
Shweta
Author by

Shweta

IT professional with close to 8 years of experience in big data, recommendation systems, data science and aws.

Updated on December 01, 2020

Comments

  • Shweta
    Shweta over 3 years

    Can structures contain functions?

  • detly
    detly over 13 years
    Who says you can't have function pointers in a struct in C?
  • Jens Gustedt
    Jens Gustedt over 13 years
    Yes, it seems you are mixing things up. Function pointers are allowed, functions themselves not.
  • JoshMachine
    JoshMachine over 13 years
    So is this also one of the difference b/w struct and classes? Because as of i know only difference is struct have default public and class is default private
  • paxdiablo
    paxdiablo over 13 years
    @Josh, I think you're actually right about the public/private being the only difference between struct/union in C++. This question was about C. I suspect functions are allowed in C++ since struct xyz { int fn(void); } a; worked just fine in g++.
  • Tony Delroy
    Tony Delroy over 13 years
    "contain data types" is a dangerously ambiguous (at least to a C++ user, where they can declare types) - "contain data" seems more accurate. All made clear in the Standard though... :-).
  • Tony Delroy
    Tony Delroy over 13 years
    Well, they're pointers to functions - much the same, except it takes some effort to initialise them, there's a risk of trying to use them when they're NULL or otherwise invalid, and they can be changed at run time....
  • caf
    caf over 13 years
    The parantheses around commTcp.open are unnecessary.
  • prap19
    prap19 over 13 years
    you can actually see examples of functions in structures in Linux kernel code. Check out linux kernel : Documentation/vfs.txt
  • Chris Reid
    Chris Reid almost 7 years
    callback is a pointer-to-function with 0 parameters returning int. C will allow you to assign to callback by reference any function matching that function signature. The use of the initialization list is what is new and special here. The printf statement is valid C, but not good style. It is confusing as to intentions and if you saw it way down far away from the struct definition you might be bewildered as to what it was and have to go hunting.