Thread: To store a function's address as an integer

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    56

    To store a function's address as an integer

    I have a struct
    Code:
    typedef struct
    {
        uint8_t type;
        uint8_t num;
        uint8_t id;
    
        int value;
    }EXPR;
    the value field is a quite multipurpose one (depending on type). one of the purposes I want to use is to store a function's address.

    The only way I found to do it
    Code:
    EXPR expr;
    
    int(*fp)(void);
    fp = Foo;
    expr.value = (int)fp;
    But how can I invoke the function?
    With the "proper" pointer I could do
    Code:
    result = fp();
    the question - can I inform a compiler that value is a function's address?
    Last edited by john7; 01-16-2022 at 09:19 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,126
    You could make a union out of it.
    Code:
    typedef struct
    {
        uint8_t type;
        uint8_t num;
        uint8_t id;
        union { 
            int value;
            int (*fp)(void);
        }v;
    }EXPR;
    Then assign with either
    Code:
    EXPR var;
    var.v.value = 42;
    var.v.fp = Foo;
    If you know it's a function, then you can just use it as a function.
    Code:
    result = var.v.fp();
    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
    May 2011
    Posts
    56
    Thanks a lot. Looks like a brilliant idea.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. create vector of objects: store address or copy?
    By deathmetal in forum C++ Programming
    Replies: 22
    Last Post: 08-20-2015, 12:20 PM
  2. how i can store 2^99999 in integer variable
    By 62049913377 in forum C Programming
    Replies: 7
    Last Post: 08-07-2010, 01:09 AM
  3. using char to store an integer in the range [128,127]
    By nikhil22 in forum C Programming
    Replies: 5
    Last Post: 07-26-2008, 09:44 AM
  4. Replies: 2
    Last Post: 12-07-2004, 02:31 AM
  5. Store Bluetooth remote address to a text file
    By labamba in forum C++ Programming
    Replies: 6
    Last Post: 07-09-2004, 06:51 AM

Tags for this Thread