Define functions in structs

C

C Problem Overview


Can we define functions in structs in C programming language?

C Solutions


Solution 1 - C

No, as functions are not data. But you can define function pointers inside a struct.

struct foo {
    int a;
    void (*workwithit)(struct foo *);
}

Solution 2 - C

You can't really declare stuff inside of a struct in C. This is not C++ or any other OO language where an object encapsulates some kind of scope.

C structs are very simple objects, it's just syntactic sugar for managing a piece of memory. When you create new struct "instance", struct A a;, compiler just reserves stack space according to its size, and when you then do a.member, compiler knows that member's offset, so it jumps to &a + offset of that member. Those offsets are usually not just sums of sizes of preceding members, because compiler usually adds some padding bits into the structure to align it nicer into memory.

Hope it helped a bit. You obviously expect slightly too much from C stuctures :-)

Solution 3 - C

I came to this post because I was looking for a way to teach a bit of Object Oriented "style" of programming in C for a very simple data structures course. I did not want to teach C++ because I did not want to keep explaining its more advanced features.

But I wanted to explore how one might implement the OO pattern used in Python but in a low-level language / run-time. By explaining what is going on in C, students might better understand the Python OO run-time patterns. So I went a bit beyond the first answer above and adapted some of the patterns from https://stackoverflow.com/a/12642862/1994792 but in a way that would elucidate OO run time patterns a bit.

First I made the "class" with a "constructor" in point.c:

#include <stdio.h>
#include <stdlib.h>

struct point
{
    int x;
    int y;
    void (*print)(const struct point*);
    void (*del)(const struct point*);
};

void point_print(const struct point* self)
{
    printf("x=%d\n", self->x);
    printf("y=%d\n", self->y);
}

void point_del(const struct point* self) {
  free((void *)self);
}

struct point * point_new(int x, int y) {
    struct point *p = malloc(sizeof(*p));
    p->x = x;
    p->y = y;
    p->print = point_print;
    p->del = point_del;
    return p;
}

Then I imported the class, constructed an object from the class, used the object, then destructed the object in main.c

#include "point.c"

int main(void)
{
    struct point * p3 = point_new(4,5);
    p3->print(p3);
    p3->del(p3);
}

It feels very "Pythonic in C".

Solution 4 - C

No, you cannot have functions inside struct in a C program. I wrote a single code and saved that as a .c and a .cpp. The .cpp file complies and works as expected, but the .c file doesn't even compile.

Here is the code for your reference. Save it once as .cpp and then run it. Then save the same code as .c and compile it. You will get a compilation errors.

#include <stdio.h>
struct C {
    void Test(int value) {
       static int var = 0;
       if (var == value) 
          printf("var == value\n");
       else
          printf("var != value\n");

       var = value;
     }
 }; 

 int main() {
    C c1;
    C c2;
    c1.Test(100);
    c2.Test(100);
    int ii;
    scanf("%d",&ii);
 }

Solution 5 - C

No.

You can have function pointers in structs, but that's as close as you'll get.

Solution 6 - C

No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result.

Solution 7 - C

No, You cant define functions inside structures in C programs, However if the extension of your file is .cpp (that is not C), you can have member functions like classes however the default modifier of these functions will be 'public'(unlike class).

Read these links for more information on Structures a good link , another good link, One more good link

As a convention in C++, Classes are used for storing functions and variables both and Structures are used only for storing information (i.e. data).

Solution 8 - C

No, but you can in c++ struct!

Solution 9 - C

You can in C++ instead:

// Example program
#include <iostream>
#include <string>

struct Node
{
    int data; Node *prev,*next;
    Node(int x, Node* prev=NULL, Node* next=NULL)
    {
        this->data=x; this->prev=prev; this->next=next;
    }
    void print_list()
    {
        Node* temp=this;    //temp is created in function call stack
        while(temp!=NULL)
        {
            std::cout<<temp->data<<" ";
            temp=temp->next;
        }
    }
    Node* insert_left(int x)
    {
        Node* temp=new Node(x,this->prev,this);
        this->prev=temp;
        return temp;                            //list gets new head
    }
    Node* insert_right(int x)
    {
        Node* temp=new Node(x,this,this->next);
        this->next=temp;
        return this;                            //this would still be head
    }
    
};

int main()
{
    Node* head=new Node(-1);	//-1
    head=head->insert_left(0);	//0 -1
	head=head->insert_right(1);	//0 1 -1
	head=head->insert_left(2);	//2 0 1 -1
    head->print_list();
}
 

Solution 10 - C

You can use only function pointers in C. Assign address of real function to that pointer after struct initialization, example:

#include <stdio.h>
#include <stdlib.h>

struct unit
{
  int result;
  int (*add) (int x, int y);
};

int sumFunc(int x, int y) { return x + y; }

void *unitInit()
{
  struct unit *ptr = (struct unit*) malloc(sizeof(struct unit));
  ptr->add = &sumFunc;
  return ptr;
}

int main(int argc, char **argv)
{
  struct unit *U = unitInit();

  U->result = U->add(5, 10);

  printf("Result is %i\n", U->result);

  free(U);

  return 0;
}

Good example of using function pointers in a struct you can find here https://github.com/AlexanderAgd/CLIST Check header and then clist.c file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionprehistoricpenguinView Question on Stackoverflow
Solution 1 - CglglglView Answer on Stackoverflow
Solution 2 - CtchapView Answer on Stackoverflow
Solution 3 - CdrchuckView Answer on Stackoverflow
Solution 4 - CSonu MishraView Answer on Stackoverflow
Solution 5 - CMatView Answer on Stackoverflow
Solution 6 - CDiego AllenView Answer on Stackoverflow
Solution 7 - CAmitView Answer on Stackoverflow
Solution 8 - CNDEthosView Answer on Stackoverflow
Solution 9 - CHimanshu TanwarView Answer on Stackoverflow
Solution 10 - CAlexanderView Answer on Stackoverflow