0
void function(int entry, int x1, int x2)
{
    void (*new_func)(int n1, int n2);
    new_func = (void (*)(int, int)) entry;
    
    new_func(x1,x2);
    
}

Lets say we have this function, there is a function new_func which is declared and defined and called from within the function. Is this allowed ? Is this possible ?

This code is compiling but while debugging it seems to be exiting.

zidane42
  • 3
  • 2

2 Answers2

1

Nested functions are not a part of the standard. However, some compilers support this as extensions. Like gcc. Read more about nested functions in C here Nested function in C

However, that's not what's going on here. In your code it's a function pointer. Read more about that here: How do function pointers in C work?

And without seeing the whole code, I'd say that entry probably has wrong type. It should probably be intptr_t or uintptr_t. What is the uintptr_t data type?

klutt
  • 30,332
  • 17
  • 55
  • 95
1

First of all, new_func is not a function, it's a function pointer.

The code snippet that you have shown in your question is casting an int value to a function pointer of type void (*)(int, int) and assigning it to new_func:

new_func = (void (*)(int, int)) entry;

but you haven't mentioned what argument is passed to entry parameter of function() function.
Are you type casting a function pointer to int and passing it as first argument to function function()?

Your program can either have implementation defined behaviour or undefined behaviour depending on value of first argument passed function() function.

From C11#6.3.2.3p5

5 An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.67)

From C11#6.3.2.3p6

6 Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

H.S.
  • 11,654
  • 2
  • 15
  • 32