Array of pointer-to-functions

L

Luca Risolia

Juha Nieminen said:
You must be joking.

You conveniently omitted the context, was "declare where used".

$ g++ -o /tmp/bbb /tmp/a.cpp
/tmp/a.cpp: In function 'int main(int, char**)':
/tmp/a.cpp:27:1: error: jump to label 'leave' [-fpermissive]
/tmp/a.cpp:19:12: error: from here [-fpermissive]
/tmp/a.cpp:23:7: error: crosses initialization of 'int b'

There is no need of goto in your example to release the lock, hence
there is no need to define variables "at the beginning of the block"
(far from where they are used) to avoid the cross initialization. Using
the RAII idiom makes programs less error-prone, shorter and let you
initialize variables where they are used:

pthread_mutex_t lock;

int
main(int arg, char **argv)
{
int a = strtoul(argv[1], NULL, 0);

pthread_mutex_init(&lock, NULL);

struct Lock {
Lock() noexcept { pthread_mutex_lock(&lock); }
~Lock() { pthread_mutex_unlock(&lock); }
} lock;

a = a + 1;
if (a == 3)
return EXIT_SUCCESS;
a = a + 3;

int b = a;

printf("%d\n", b);

return EXIT_SUCCESS;
}
 
I

I

You already have an index into the array (or vector). There is no need for a switch. The switch is redundant. See below: for(int i=0;i<size_choice;i++) { cin>>choice; // Choice is already an index into the // array of function pointers... Get it? (*array_of_pointers[choice])(...); }

Ahh yep. Thanks.
 
I

Ian Collins

Juha Nieminen said:
You must be joking.

You conveniently omitted the context, was "declare where used".

$ g++ -o /tmp/bbb /tmp/a.cpp
/tmp/a.cpp: In function 'int main(int, char**)':
/tmp/a.cpp:27:1: error: jump to label 'leave' [-fpermissive]
/tmp/a.cpp:19:12: error: from here [-fpermissive]
/tmp/a.cpp:23:7: error: crosses initialization of 'int b'

Those are a consequence of writing spaghetti code rather than
initialising a variable where it is used! It's good to see compilers
issuing such errors.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top