Re: Exercise with array of pointers to func
"Alex Blekhman" wrote:
"Fil" wrote:
#include <iostream>
You forgot to #include <string>. Operator << for `std::string' is
defined there.
How stupid! I feel ashamed to bother you for such a thing. Luckily I had a
second questions in my thread.
using namespace std;
// A macro to define dummy functions:
#define DF(N) string N() { \
return "function " #N " called..."; }
You can use predefined macro for function name:
#define DF(N) string N() { \
return "function " __FUNCTION__ " called..."; }
that's good to know
DF(a); DF(b); DF(c); DF(d); DF(e); DF(f); DF(g);
The semicolon after the D macro is redundant.
You mean I could write
DF(a) DF(b) DF(c) DF(d) DF(e) DF(f) DF(g)
since there are already braces to tel the compiler when the definition stops
as for every function. True, thanks.
string ((*(func_table[]))()) = { &a, &b, &c, &d, &e, &f, &g };
First of all, I'd suggest to use a typedef here, which will
simplify the code greatly:
typedef string (*my_func_t)();
ok
Second, the name of a function is already a pointer. No need for
operator &:
I thought the same for the name of an array and, as per our conversations in
other threads, I reached the conclusion that it was better, at least for
arrays, to use the reference & operator when I want to get its address
(whether with the array name &array, if I want to assign its address to a
pointer to an array of its type, or with its first element &(array[0]) if I
want to assign its address to a pointer pointing to an element of its type.
In fact in the book the example is written without the reference operator &.
Since both are possible with functions I'd rather state explicitely (my
choice) that I am putting into these pointers the addresses of those
functions.
my_func_t func_table[] = { a, b, c, d, e, f, g };
cout << ((*(func_table[c - 'a']))()) << endl;
Too many parentheses. You can write it like that:
I know I have this horrible style but it gives me enormous confidence while
reading what it is:
Reading outwards
the 1st set of parenthesis tells me : it's an array
the 2nd set of parenthesis tells me : of pointers
the 3nd set of parenthesis tells me : to functions taking no params
That's the method of Bruce Eckel in "Thinking in C++" (he writes less
parenthesis than me though).
Since:
- I don't know which ones I can remove without creating confusion to the
compiler (it creates cofusion to me anyway)
- I know that if I put them all it's clear to both of us (the compiler and
me) what it means
I decided to write them all until I found another lighter but consistent
method.
cout << func_table[c - 'a']() << endl;
HTH
Alex