Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking the address of a function from within that function

First, the question: Is there any reason you can't take the address of a function from within that function?

#include <stdio.h>

struct foo {
  void(*xf)(void);
  int r;
} sFoo;

void func(void) {
  sFoo.xf = func; /* <-- like this */
}

int main()
{
  func();
  printf("FuncPtr  is: %p\n", sFoo.xf);
  printf("FuncAddr is: %p\n", &func);
  getchar();
  return 0;
}

I can't think of a reason why this shouldn't work portably, but that doesn't mean there isn't one. I've tested it with MinGW and MSVC on Windows, and gcc on Ubuntu, and it works fine. The C standard is pretty much silent, except to say that (C99 5.1.1.2) function references are resolved in the final translation phase.

My main aggravation is that I can't find anything that confirms that this is standard behavior. I've run across comments in the past that said that you couldn't take the address of a function from within that function, which I thought were bogus at the time, but didn't really have the time or inclination to actually check it out, until now.

like image 617
Mark Benningfield Avatar asked Dec 24 '22 11:12

Mark Benningfield


1 Answers

Is there any reason you can't take the address of a function from within that function?

Nope.

The C standard is pretty much silent, except to say that (C99 5.1.1.2) function references are resolved in the final translation phase.

The standard is not silent; it just does not address that particular case explicitly. It is not a special case.

My main aggravation is that I can't find anything that confirms that this is standard behavior.

The standard specifies that you can obtain the address of a function, and it describes how. It makes no exception for code inside the function's definition, so the general rules apply there. It would in fact be pretty inconsistent if you could not obtain a pointer to a function within that function's implementation, since you can certainly call it from there (i.e. recursively).

I've run across comments in the past that said that you couldn't take the address of a function from within that function, which I thought were bogus at the time, but didn't really have the time or inclination to actually check it out, until now.

I'm inclined to agree that such comments were mistaken to whatever extent they were directed at standard C. Perhaps, though, they were directed at some non-conforming implementation. Or perhaps you misremember. Obviously, I cannot address any such comments with specificity unless you provide a reference, and preferrably an in-context quotation in your question.

like image 163
John Bollinger Avatar answered Mar 08 '23 05:03

John Bollinger