473,385 Members | 1,341 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

table of function calls: need sample code

Hello, All!

I started to implement simple command line interface (CLI), and wanna
know how to use table of fucntion calls. Could you please, recommend me some
link or give example directly in conference?

Thanks in advance!

With best regards, Roman Mashak. E-mail: mr*@tusur.ru
Nov 14 '05 #1
8 1648
Me
> I started to implement simple command line interface (CLI), and wanna
know how to use table of fucntion calls. Could you please, recommend me some
link or give example directly in conference?


Not the greatest example in the world but it should get you started:

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

enum NextThing { GET, PRINT, BYEBYE };

enum NextThing nextThing;
int ch;

void get()
{
ch = getc(stdin);
nextThing = (ch != EOF) ? PRINT : BYEBYE;
}

void byebye() { exit(0); }

void print() { fputc(ch, stdout); nextThing = GET; }

void (* const ftable[])() = {
get,
print,
byebye
};

int main()
{
for (;;)
ftable[nextThing]();
return 0;
}

Nov 14 '05 #2
Hello, Me!
You wrote on 7 Jun 2005 22:49:49 -0700:

M> enum NextThing { GET, PRINT, BYEBYE };

M> enum NextThing nextThing;
M> int ch;

M> void get()
M> {
M> ch = getc(stdin);
M> nextThing = (ch != EOF) ? PRINT : BYEBYE;
M> }

M> void byebye() { exit(0); }

M> void print() { fputc(ch, stdout); nextThing = GET; }

M> void (* const ftable[])() = {
M> get,
M> print,
M> byebye
M> };

M> int main()
M> {
M> for (;;)
M> ftable[nextThing]();
M> return 0;
M> }

I'm not sure I understood well - how will the function 'ftable[nextThing]()'
know what index to pickup? Could ypu please clear up this?

With best regards, Roman Mashak. E-mail: mr*@tusur.ru
Nov 14 '05 #3
Me
> M> enum NextThing { GET, PRINT, BYEBYE };

GET==0
PRINT==1
BYEBYE==2

we use these to index into the ftable array
M> enum NextThing nextThing;
nextThing initialized to GET, so the get function is the first one we
call.
M> int ch;

M> void get()
M> {
M> ch = getc(stdin);
M> nextThing = (ch != EOF) ? PRINT : BYEBYE;
M> }
Read a character from stdin and save it in the global variable ch. If
we reached the end, call the byebye function on the next iteration,
else call the print function
M> void byebye() { exit(0); }
exit(0) quits the program. This will terminate the infinite loop down
in main
M> void print() { fputc(ch, stdout); nextThing = GET; }
print ch out and and call get on the next iteration to read another
character. You can see we are bouncing back and forth between get and
print until we reach the end of the stream.
M> void (* const ftable[])() = {
M> get,
M> print,
M> byebye
M> };
ftable[GET] == &get
ftable[PRINT] == &print
ftable[BYEBYE] == &byebye

To make the type easier to understand, you can also use typedefs:

typedef void (*FN)(void);

FN is a pointer to a function taking no parameters and returning
nothing

FN ftable[3] = { get, print, byebye };

ftable is a 3 element array of function pointers
M> int main()
M> {
M> for (;;)
M> ftable[nextThing]();
M> return 0;
M> }

I'm not sure I understood well - how will the function 'ftable[nextThing]()'
know what index to pickup? Could ypu please clear up this?


ftable is an array of function pointers (you can't create an array of
functions by the way for various reasons). You index it with nextThing
as the index. The print and get functions modify the nextThing index
depending on the state. For example:

void (*fnptr)() = ftable[1];

copies the function pointer at ftable[1] (&print in this case) over to
the variable fnptr. Now, we can call the function by using fnptr(). You
could have also called it without the temporary variable by using
ftable[1]().

You should probably step through this code with a debugger to examine
what's going on at each step if you still don't get it.

Nov 14 '05 #4
Roman Mashak <mr*@tusur.ru> wrote:
Hello, Me!
You wrote on 7 Jun 2005 22:49:49 -0700:
enum NextThing { GET, PRINT, BYEBYE }; enum NextThing nextThing;
int ch; void get()
{
ch = getc(stdin);
nextThing = (ch != EOF) ? PRINT : BYEBYE;
} void byebye() { exit(0); } void print() { fputc(ch, stdout); nextThing = GET; } void (* const ftable[])() = {
get,
print,
byebye
}; int main()
{
for (;;)
ftable[nextThing]();
return 0;
}

I'm not sure I understood well - how will the function 'ftable[nextThing]()'
know what index to pickup? Could ypu please clear up this?


'ftable' isn't a function but an array of function pointers. And
'ftable[nextThing]' is a pointer to the element with index 'nextThing'
in this array, which, of course, is a function pointer. When you write
a function pointer followed by parentheses then the function this
pointer points to gets invoked. So the line

ftable[ 0 ]( );

is a call of get(),

ftable[ 1 ]( );

is a call of print() and, finally,

ftable[ 2 ]( );

is a call of byebye().

And 'nextThing' is a global variable, so it's initialized automatically
to 0 and the first thing done in main is calling get(). And in get() as
well as print() 'nextThing' always gets assigned a new value print()
sets it to 0 each time and in get() it gets set according to the user
input (either to 1 or 2).
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #5
Hello, Me!
You wrote on 8 Jun 2005 06:05:38 -0700:

M> copies the function pointer at ftable[1] (&print in this case) over to
M> the variable fnptr. Now, we can call the function by using fnptr(). You
M> could have also called it without the temporary variable by using
M> ftable[1]().

Thanks very much to you and Jens Thoms Toerring for detailed explanation!

Regarding to my program (simple command line interface).
The command line has the following style:
<cmd_action> <arg1> <arg2> ... <argN>

I'm going to use 2 tables (arrays): one will contain <cmd_action> names and
the second will contain the functions pointers processing every command (i
guess it's correct way). It means I'll need some keys for finding matches
between tables, right?

So, waht I'd like to know is how can I implement this in C, I'm not quite
sure about keys in tables...

Anyway, thanks for any advice!

With best regards, Roman Mashak. E-mail: mr*@tusur.ru
Nov 14 '05 #6
Me
> Regarding to my program (simple command line interface).
The command line has the following style:
<cmd_action> <arg1> <arg2> ... <argN>

I'm going to use 2 tables (arrays): one will contain <cmd_action> names and
the second will contain the functions pointers processing every command (i
guess it's correct way). It means I'll need some keys for finding matches
between tables, right?
One way to do this is to get a complete line from stdin, this requires
dynamic array allocation (and resizing) unless you want to hardcode the
max length of a line.

The next step is to take this line and tokenize it into smaller
substrings. You're basically doing the same code that the runtime does
to convert what you type in at a terminal to run your program into the
argv array that gets passed as the 2nd parameter to main. This part is
optional, you could just pass in the whole line to the function but
then each function has to do its own parameter parsing. There are
tradeoffs to both ways but tokenizing it into smaller substrings is
probably the way to go.

The next step is to take the first substring and map it to a function.
The easiest way is to just use a bunch of if statements with strcmp (or
stricmp if your platform has it), you don't even need function pointers
for this. The other ways (which all involve function pointers) are to
keep a sorted table and use binary search, use a sorted linked list and
linearly look through it, use a hash table, use a binary tree, etc.
Once you map the string to the function, just call it with in the
tokenized array.
So, waht I'd like to know is how can I implement this in C, I'm not quite
sure about keys in tables...


The above takes a bit of code to do in C because I'm assuming you want
to learn how to do it yourself instead of using somebody else's
functions. I'd highly suggest you get this book
http://cm.bell-labs.com/cm/cs/tpop/ because it pretty much is perfect
for somebody with your experience and it covers everything you need to
know to write something like that (and then some).

Nov 14 '05 #7
Hello, Me!
You wrote on 9 Jun 2005 01:21:51 -0700:

[skip]
M> The next step is to take the first substring and map it to a function.
M> The easiest way is to just use a bunch of if statements with strcmp (or
M> stricmp if your platform has it), you don't even need function pointers
M> for this. The other ways (which all involve function pointers) are to
M> keep a sorted table and use binary search, use a sorted linked list and
M> linearly look through it, use a hash table, use a binary tree, etc.
M> Once you map the string to the function, just call it with in the
M> tokenized array.
Thanks, this is the way I assumed to follow. Frankly speaking I would not
mind to find some example source code for reference. Could you recommend me
some? For example, simple implementation of binary search, or sorted lined
list, CLI is also welcome.

All I want now - is understand some major concepts and algorithms.

With best regards, Roman Mashak. E-mail: mr*@tusur.ru
Nov 14 '05 #8
Roman Mashak wrote:
.... snip ...
Thanks, this is the way I assumed to follow. Frankly speaking I
would not mind to find some example source code for reference.
Could you recommend me some? For example, simple implementation
of binary search, or sorted lined list, CLI is also welcome.

All I want now - is understand some major concepts and algorithms.


I think the example wdfreq.c, showing a usage of the hashlib
package, will do what you want. It scans an input file, extracts
words, counts duplicates, forms a singly linked list of the
results, sorts that alphabetically and by count, and dumps the
result. It uses a stable sort, namely mergesort. Heavily
commented. You can get the whole package at:

<http://cbfalconer.home.att.net/download/hashlib.zip>

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: serge | last post by:
Using "SELECT * " is a bad practice even when using a VIEW instead of a table? I have some stored procedures that are identical with the difference of one statement in the WHERE clause. If I...
6
by: AFN | last post by:
I have a server-side table, <asp:table id="tblData" EnableViewState="true" runat="server" /> and my code-behind adds rows of data to the table in code that says: if not page.ispostback then...
6
by: Todd A. Anderson | last post by:
I have a function foo of which I need to get the address. The problem is that when you say "&foo" (or just foo for that matter), you get the address of this function's entry in a jump table and...
21
by: Johan Tibell | last post by:
I would be grateful if someone had a minute or two to review my hash table implementation. It's not yet commented but hopefully it's short and idiomatic enough to be readable. Some of the code...
28
by: Larax | last post by:
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) {
4
by: Bob | last post by:
Hi all, I've got a table that I've imported and it has junk at the top of the table, so after import I run a delete query to remove the junk lines then I'm left with the field names I want for...
6
by: Romulo NF | last post by:
Greetings again to everyone, Im back to show this grid componenet i´ve developed. With this grid you can show the data like a normal table, remove the rows that you need, add rows, import data,...
5
by: Romulo NF | last post by:
Greetings, I´m back here to show the new version of the drag & drop table columns (original script ). I´ve found some issues with the old script, specially when trying to use 2 tables with...
9
by: =?Utf-8?B?RGFya21hbg==?= | last post by:
Hi, I am wondering how you multi-dimension an array function? My declared function looks like this: Public Function GetCustomerList(ByVal Val1 As String, ByVal Val2 As Long, ByVal Val3 As...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.