C Structures
I haven't completely programmed in C for about 2 years so please excuse if I sound uninformed but I was trying to program a little tutorial in C and I was making a structure for properties of a car. Now back when I learned C in college we never declared functions in a structure because well as far as I remember I thought you can't declare functions in structures, that only came in C++ with classes. Anyway I decided "what the hell..." and I plugged in a function in the struct just to test it out and to my surprise it compiled and ran without a hitch. Now is it possible that I just didn't listen in C class when they explained declaring functions in structs or is it my compiler using good ol C++ to make that possible.
Hope someone can clear this up for me. :D
Odds are you're using a C++ compiler. In a C++ compiler, the only difference between struct and class is that struct defaults to public and class defaults to private. You can put member functions in a struct in C++.
In C, you can put function pointers in your structure, like this
In C, you can put function pointers in your structure, like this
struct Blah{ int x; void (* AddToX)(struct Blah *pThis);}void myAddFunc(struct Blah *pThis){ pThis->x++;}int main(void){ struct Blah myBlah; myBlah.AddToX = myAddFunc; myBlah.x = 0; myBlah.AddToX(&myBlah);}
Perfect! I remember now we did use pointers to functions. Thanks a lot for the info and quick too! :D
If you want your C++ compiler to treat your code as C code, give your source file a ".c" extension.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement