Thread: Function pointer array with immediate initalization with nameless functions

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jan 2020
    Posts
    7

    Function pointer array with immediate initalization with nameless functions

    What I'm trying to do is make an array of functions, and initialize it with "anonymous" functions. That is, the function is only defined inside of the array. I currently use an enum to simulate calling the function by name but you could just as well call it with functions[0]. But I can't figure out the syntax: the compiler says "error: ‘i’ undeclared (first use in this function)".


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define break_code
    
    int print_add(int i){
        printf("%d\n", ++i);
        return i;
    }
    
    int main(int argc, char const *argv[])
    {
        enum {printadd=0};
        int (*functions[1])(int i) = {
    
            #ifdef break_code
            (int(*)(int i)){
                printf("%d\n", ++i);
                return i;
            }
            #endif
    
        };
    
        #ifndef break_code
        functions[printadd] = print_add;
        #endif
    
        // b will be 6
        int b = functions[printadd](5);
    
        return 0;
    }
    In javascript, this would be something like

    Code:
    functions = { print_add: function(i){i++; console.log(i); return i;} };
    Last edited by midyro edellve; 12-20-2020 at 07:27 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 10-20-2019, 02:00 PM
  2. Passing 2D array to function via pointer of pointer
    By sean_cantab in forum C Programming
    Replies: 4
    Last Post: 05-09-2016, 10:15 AM
  3. Question: Can a function be nameless?
    By Omega Metroid in forum C++ Programming
    Replies: 20
    Last Post: 09-29-2009, 05:48 PM
  4. templates and nameless namespaces
    By King Mir in forum C++ Programming
    Replies: 25
    Last Post: 06-02-2008, 07:22 AM
  5. Replies: 2
    Last Post: 11-22-2001, 12:22 PM

Tags for this Thread