0

C and C++ documentation for the use of #define suggests that this should not work as I am using the define to replace the text MyFunc() with _myfunc(), which is a function that does not exist:

#define MyFunc _myfunc

void MyFunc()
{
    cout << "This Prints!" << endl;
}

int Main()
{
    _myfunc();
    return 0;
}

My guess is that the compiler is being clever. It knows that _myfunc() does not exists and therefore does not replace the text and simple uses MyFunc().

I can't find any documentation to support this theory. Does anyone know whether this is correct?

  • 7
    `#define` is a preprocessor macro. Preprocessor runs before the compiler, hence - the compiler doesn't even see any `#define`s, so it can't be clever (or not) about those. – Algirdas Preidžius Jun 04 '21 at 11:09
  • Does this answer your question? [How do I see a C/C++ source file after preprocessing in Visual Studio?](https://stackoverflow.com/questions/277258/how-do-i-see-a-c-c-source-file-after-preprocessing-in-visual-studio) – GSerg Jun 04 '21 at 11:10
  • 6
    Your guess was incorrect. `void MyFunc()` gets replaced by `void _myfunc()`, because that's how `#define` works, and nothing exciting happens when `main` gets compiled. – Sam Varshavchik Jun 04 '21 at 11:11

1 Answers1

4

After the preprocessor has run, your program will look like:

void _myfunc()
{
    cout << "This Prints!" << endl;
}

int Main()
{
    _myfunc();  // #1
    return 0;
}

Ignoring other errors here (lack of includes, ...), the compiler can find _myfunc declared and defined, so naturally it will be found by overload resolution at the call site #1.

dfrib
  • 70,367
  • 12
  • 127
  • 192