Solved

Is it possible to have a function inside a struct?

Posted on 2006-11-30
2
191 Views
Last Modified: 2010-04-15
Hi Experts,
Is it possible to have a function inside a struct, if so, can anyone tell me how?

-Rahul
0
Comment
Question by:rrahulgupta
2 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 18048359
That's possible in C++, in C, you could only place a function pointer inside a struct, e.g.

int add(int a, int b) { return a + b;}

typdef int (*FuncPtr)(int,int);

struct foo {

int a;
int b;
FuncPtr ptr;
};

struct foo test;
int result;

test.a = 1;
test.b = 2;
test.ptr = add;

result = (*test.ptr)(test.a,test.b);

Clumsy, isn't it?
0
 

Author Comment

by:rrahulgupta
ID: 18048489
yeah, it is. :-)
anyway, thanks for the comment.
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question