Thread: Function pointer array with immediate initalization with nameless functions

  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.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Yeah, they're called lambdas in C++
    Lambda expressions (since C++11) - cppreference.com

    But C has no such thing.

    You can only point at named functions.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jan 2020
    Posts
    7
    Ah, I see. No big problem, I just wanted to see if it could be done and how. Thanks!

  4. #4
    Registered User
    Join Date
    Dec 2020
    Posts
    4
    You're not using the compound literal operator correctly.

    In between the parentheses, only the type is meaningful. Declaring i as an int is completely useless. The compiler ignores i.

    In between the curly brackets, you must give a value that matches the type enclosed in the preceding parentheses.

    Examples:

    Code:
    (int) {23}
    
    (char []) {"abc"}
    
    (int (*)(int)) {print_add}
    To make your code work,

    Code:
    #include <stdio.h>
    
    
    #define break_code
    
    
    int print_add(int i)
    {
        printf("%d\n", ++i);
        return i;
    }
    
    
    int main(void)
    {
        enum { printadd = 0 };
    
    
        int (*functions[1])(int) = {
     
            #ifdef break_code
            (int (*)(int)) {
                print_add
            }
            #endif
     
        };
    
    
        // b will be 6
        int b = functions[printadd](5);
    
    
        printf("b = %d\n", b);
     
        return 0;
    }

    However, using the compound literal operator is completely redundant here and wastes space as it allocates memory to store the function pointer.

    So, instead,

    Code:
    #include <stdio.h>
    
     
    #define break_code
     
    int print_add(int i)
    {
        printf("%d\n", ++i);
        return i;
    }
     
    int main(void)
    {
        enum { printadd = 0 };
    
    
        int (*functions[1])(int) = {
     
            #ifdef break_code
            print_add
            #endif
     
        };
    
    
        // b will be 6
        int b = functions[printadd](5);
    
    
        printf("b = %d\n", b);
     
        return 0;
    }
    Last edited by magno; 12-24-2020 at 07:01 AM.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    magno, you might want to read the question and the following discussion too rather than just the code posted. The code that you offer as a solution is "wrong", not because it is syntactically or even logically incorrect, but because the request was for how to declare and use an anonymous function, whereas your code makes use of the named function print_add. The correct answer has already been given: C has no anonymous functions.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Dec 2020
    Posts
    4
    Quote Originally Posted by laserlight View Post
    magno, you might want to read the question and the following discussion too rather than just the code posted. The code that you offer as a solution is "wrong", not because it is syntactically or even logically incorrect, but because the request was for how to declare and use an anonymous function, whereas your code makes use of the named function print_add. The correct answer has already been given: C has no anonymous functions.


    laserlight, I know someone has told OP there's no anonymous function in C. However, does OP know how to use compound literals? He wouldn't have made such a glaring mistake if he knew.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    It should be obvious from context that it was an attempt at guessing the syntax of an anonymous function in C, i.e., it has nothing to do with compound literals. That's why there was a printf call and a return statement right in the middle of it.
    Last edited by laserlight; 12-24-2020 at 05:00 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User
    Join Date
    Dec 2020
    Posts
    4
    OP clearly tried to use compound literal in her/his attempt, and yet you still think no compound literals were involved? Whatever makes you happy man.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by magno
    OP clearly tried to use compound literal in her/his attempt, and yet you still think no compound literals were involved?
    No, the OP did not try to use a compound literal. The context is "what is the syntax for an anonymous function?" In this context, the code looks like an attempt to try writing an anonymous function that returns an int and has a parameter of type int named i, with this as the function body:
    Code:
    printf("%d\n", ++i);
    return i;
    It coincidentally looks like a very malformed compound literal, if you had no clue as to the context, but since the context was provided, it obviously has nothing to do with a compound literal. This is my point: it is very good to contribute, but read the question for the context rather than jumping to conclusions with wrong assumptions about the code.

    EDIT:
    Granted, the code might be a bit confusing because midyro edellve included some testing code that demonstrated what they wanted if it was done without anonymous functions, but if we were to rephrase the question and code without this testing code, it would essentially be: given this code, declare an array of anonymous functions named functions such that the first element of the array is equivalent to this function:
    Code:
    int print_add(int i){
        printf("%d\n", ++i);
        return i;
    }
    This is the given code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char const *argv[])
    {
        enum {printadd=0};
    
        // Define the anonymous array of functions here:
        // ...
    
        // b will be 6
        int b = functions[printadd](5);
    
        return 0;
    }
    It is forbidden to define any other functions besides anonymous functions.

    Now it might be clearer why your help is mistaken: you cannot use print_add in your example because print_add is not an anonymous function. You can talk until the cows come home about compound literals, but compound literals will never solve this problem. The solution is simply to recognise that C doesn't have anonymous functions, and that was done before your first post in this topic. Please don't be discouraged from contributing: I'm just pointing out that it is important to read the context.
    Last edited by laserlight; 12-24-2020 at 09:09 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Dec 2020
    Posts
    4
    Sigh... you’re missing my point completely. The reason I posted about compound literal is that if OP knew how to use it properly, OP wouldn’t have tried to use it to make an anonymous function. You just don’t see the bigger picture.

    Also, there’s no need to randomly attack someone who was just trying to help out. Merry Christmas and chill m8

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by magno
    The reason I posted about compound literal is that if OP knew how to use it properly, OP wouldn’t have tried to use it to make an anonymous function.
    Ah, then instead of saying "you're not using the compound literal operator correctly", it would have been clearer to say: "the syntax that you attempted to use looks like a compound literal, but of course as you discovered it is invalid. If you did want to use a compound literal instead of attempting an anonymous function, then this is how you would do it".

    Quote Originally Posted by magno
    You just don’t see the bigger picture.
    Well, your answer didn't answer the question, and you didn't explain why. That's not a "bigger picture" until you provide your own context.

    Quote Originally Posted by magno
    Also, there’s no need to randomly attack someone who was just trying to help out. Merry Christmas and chill m8
    No, not attacking you. I was explaining why you need to answer according to the context provided. Anyway, merry Christmas!
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

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