Sign in to follow this  

C Structures

This topic is 4838 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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

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);
}

Share this post


Link to post
Share on other sites

This topic is 4838 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this