top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Is it possible to define a formula in C struct?

0 votes
563 views

Something like or anything similar

typedef struct {
    int a,b;
    float y=a/b;
}x;
posted Sep 28, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

No, you cannot define a function within a struct in C.

You can have a function pointer in a struct though but having a function pointer is very different from a member function in C++, namely there is no implicit this pointer to the containing struct instance.

Contrived example:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct point
{
    int x;
    int y;
    void (*print)(const struct point*);
};

void print_x(const struct point* p)
{
    printf("x=%d\n", p->x);
}

void print_y(const struct point* p)
{
    printf("y=%d\n", p->y);
}

int main(void)
{
    struct point p1 = { 2, 4, print_x };
    struct point p2 = { 7, 1, print_y };

    p1.print(&p1);
    p2.print(&p2);

    return 0;
}
answer Oct 1, 2015 by Shivaranjini
...