I need to create an arrangement of procedures in c , I did it in this way but I get an error:
typedef void TFunc;
int main{
TFunc funciones[25] = {definicion de mis funciones};
}
TL; DR: Skip to the second "subtopic" if you find it boring as follows:)
What you propose, I personally consider it bad practice due to the number of arguments that a function can have and so on, but it is totally possible to achieve it while the functions that you are going to store have the same signature 1 .
I will start by breaking down your problem:
When doing:
typedef void TFunc;
You are creating a kind of "alias" for the word void
, which has a null effect, because void
(Alias TFunc
) resolve to:
void funciones[25] = { /* ... */ };
And this is simply frowned upon by the C compiler.
And your second mistake:
int main { /* ... */ }
In C (And in practically any programming language) parentheses are mandatory both when calling, and when defining or declaring a function, so that simply generates Compilation errors 2 .
To begin with, we must recognize the signature of functions that we want the array of functions we are going to build to have, in my case, I have selected int Funcion(int);
, to make it simple.
We create a typedef
to improve the view:
typedef int (*TFunc)(int); /* Creamos un "alias" para el puntero a función */
/* El alias definido arriba es una función que retorna un entero
y acepta un entero como argumento, puedes cambiarlo como necesites. */
We define some functions that comply with the same signature 1 as the "alias" defined above:
int EsMinuscula(int c) {
return (c >= 'a' && c <= 'z');
}
int EsDigito(int c) {
return (c >= '0' && c <= '9');
}
int EsControl(int c) {
return (c >= 0 && c <= ' ');
}
int EsMayuscula(int c) {
return (c >= 'A' && c <= 'Z');
}
We have some functions: D, now let's create our arrangement of function pointers 3
Now we are going to what we want to achieve! Create the function array 4 :
#include <stdio.h>
int main(void) { /* <- Eh que no se te olviden los paréntesis! */
/* Creamos arreglo para las funciones :) */
TFunc MisFunciones[] = {
EsMinuscula, EsDigito, EsControl, EsMayuscula
};
/* Vamos a hacer una prueba :) */
char *Cads[] = {
"Es Minuscula: ", "Es Digito: ", "Es Control: ", "Es Mayuscula: "
};
printf("Escribe un caracter (UNO SOLO) y presiona enter: ");
int Chr = fgetc(stdin);
for (int i = 0; i < 4; i++) {
printf("%s %s\n",
Cads[i], MisFunciones[i](Chr)? "si": "no");
}
return 0;
}
And we are ready with the theme of function pointers.
As you can see, you can not add the definition of a function within the expression used to instantiate a static array, C is a high-level language, but it is designed so that everything you want to use must be present. before using it, or, at least, having its name somewhere (Declare / Create prototypes) .
Greetings ^^
1 : Number of arguments and return type of any function.
2 : See ideone .
3 : Function pointers
4 : I leave you a repl.it to try:)