Define functions in structs

后端 未结 10 970
南旧
南旧 2020-12-08 08:58

Can we define functions in structs in C programming language?

相关标签:
10条回答
  • 2020-12-08 09:55

    No, but you can in c++ struct!

    0 讨论(0)
  • 2020-12-08 09:56

    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.

    0 讨论(0)
  • 2020-12-08 09:58

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

    0 讨论(0)
  • 2020-12-08 10:02

    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);
     }
    
    0 讨论(0)
提交回复
热议问题