A
A
Akmal Kadirov2014-08-09 23:48:08
linux
Akmal Kadirov, 2014-08-09 23:48:08

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

2 answer(s)
J
jcmvbkbc, 2014-08-09
@jcmvbkbc

You cannot create (i.e. define) a function in a structure. You can define a function pointer.

T
tsarevfs, 2014-08-10
@tsarevfs

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 question

Ask a Question

731 491 924 answers to any question