Jump to content
  • Advertisement
Sign in to follow this  
Eric Poitras

C Structures

This topic is 5056 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!