I have a code with a very long while loop. In this while loop, there is a long switch-case function in order to know which function should be applied on bar
.
int i=0;
while(i<BigNumber)
{
switch(variable)
{
case 1:
foo1(bar);
case 2:
foo2(bar);
etc...
}
i = i+1;
}
However, from one iteration to another of this while loop, the case in the switch-case structure is always the same. I would therefore, think that it would be more intelligent to define a unique function foo
to apply on bar
before the while loop but can I make this conditional definition of foo
? Something like
switch(variable)
{
case 1:
define foo this way
case 2:
define foo that way
etc...
}
int i=0;
while(i<BigNumber)
{
foo(bar);
i = i+1;
}
but one cannot define a function within main, so this code fails to compile. How can I solve this issue? Is there any way to define a function conditional to something? Does the best solution consists of making an array of pointers to functions and then call the correct function within the while loop by doing something like (*myarray[variable])(bar)
?
Here, function pointers are tailor-made to solve this type of challenge. You will define your normal functions
foo1
,foo2
, and any more you may need. You then define afunction pointer
with the syntaxreturn type (*fpointername)(arg, list);
Yourarg
,list
parameters are just thetype
for the functions to be assigned. (e.g if your functions werevoid foo1 (int a, char b)
then you declare your function pointer asvoid (*fpointername)(int, char);
(variable names omitted in fn pointer definition).The following is a simple program that illustrates the point. Drop a comment if you have any questions:
output:
To elaborate on happydave's comment