Answer the question
In order to leave comments, you need to log in
JP C: Is it possible to create a function in a struct?
JP C: Is it possible to create a function in a struct?
Answer the question
In order to leave comments, you need to log in
You cannot create (i.e. define) a function in a structure. You can define a function pointer.
Methods can be created in C++ but not in C. However, C is also written in an object-oriented style. For example, we can agree to describe methods as functions whose name prefix matches the class name, and a pointer to an instance of the class is passed as the first parameter:
struct Car
{
int speed;
int pos_x;
int pos_y;
};
void Car_set_pos(struct Car * car, int x, int y)
{
car->pos_x = x;
car->pos_y = y;
}
void Car_print_speed(struct Car * car)
{
printf("%d\n", car->speed);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question