ch3-FunctionTable (Array of pointers to functions)

Chapter_3     Exercise_3-33 Exercise_3-34







FunctionTable     TCP1, p. 216-217  (function_table.c,  FunctionTable.cpp)




function_table.c         download


// Using an array of pointers to functions
#include <stdio.h> // for printf(), getchar()

// A macro to define dummy functions:
#define DF(N) void N() \
{printf("Function %s() called...\n", #N);}

DF(a); DF(b); DF(c); DF(d); DF(e); DF(f); DF(g); // semicolons not required here

void (*func_table[])() = {a, b, c, d, e, f, g};

int main()
{
char c;

while(1)
{
printf("Press a key from 'a' to 'g' or 'q' to quit\n");
c = getchar(); getchar(); // second one for newline (ENTER)

if (c == 'q') {break;} // out of while(1)
if (c < 'a' || c > 'g') {continue;} // function not defined
// else 'a' <= c <= 'g'
(*func_table[c - 'a'])();
func_table[c - 'a'](); // same function call
}

return 0;
}
/*
gcc function_table.c -o function_table
./function_table
Press a key from 'a' to 'g' or 'q' to quit
0
Press a key from 'a' to 'g' or 'q' to quit
h
Press a key from 'a' to 'g' or 'q' to quit
a
Function a() called...
Function a() called...
Press a key from 'a' to 'g' or 'q' to quit
g
Function g() called...
Function g() called...
Press a key from 'a' to 'g' or 'q' to quit
c
Function c() called...
Function c() called...
Press a key from 'a' to 'g' or 'q' to quit
q
*/











FunctionTable.cpp         download


// Using an array of pointers to functions
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

// A macro to define dummy functions:
#define DF(N) void N() \
{cout << "Function " #N "() called..." << endl;}

DF(a); DF(b); DF(c); DF(d); DF(e); DF(f); DF(g); // semicolons not required here

void (*func_table[])() = {a, b, c, d, e, f, g};

int main()
{
char c, cr; // CR - carriage return or newline

while(1) // while(true)
{
cout << "Press a key from 'a' to 'g' or 'q' to quit" << endl;
cin.get(c); cin.get(cr); // second one for CR (ENTER)

if (c == 'q') {break;} // out of while(1)
if (c < 'a' || c > 'g') {continue;} // function not defined
// else 'a' <= c <= 'g'
(*func_table[c - 'a'])();
func_table[c - 'a'](); // same function call
}

return 0;
}
/*
g++ FunctionTable.cpp -o FunctionTable
./FunctionTable
Press a key from 'a' to 'g' or 'q' to quit
0
Press a key from 'a' to 'g' or 'q' to quit
h
Press a key from 'a' to 'g' or 'q' to quit
a
Function a() called...
Function a() called...
Press a key from 'a' to 'g' or 'q' to quit
g
Function g() called...
Function g() called...
Press a key from 'a' to 'g' or 'q' to quit
c
Function c() called...
Function c() called...
Press a key from 'a' to 'g' or 'q' to quit
q
*/









Chapter_3     Exercise_3-33 BACK_TO_TOP Exercise_3-34



Comments

Popular posts from this blog

Contents