Define functions in structs

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

Can we define functions in structs in C programming language?

10条回答
  •  南笙
    南笙 (楼主)
    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 
    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);
     }
    

提交回复
热议问题