Can we define functions in structs in C programming language?
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);
}