3

Can the name of function and function-like macro be same?
Wouldn't this cause any problem?

Pankaj Mahato
  • 1,051
  • 5
  • 14
  • 26

3 Answers3

8

They could be the same. Depending on how you use the name, either it gets replaced by preprocessor or not. For example

//silly but just for demonstration.
int addfive(int n)
{
    return n + 5;
}
#define addfive(n) ((n) + 5)

int main(void)
{
    int a;
    a = addfive(2); //macro
    a = (addfive)(2); //function
}

for ex. MS says that: http://msdn.microsoft.com/en-us/library/aa272055(v=vs.60).aspx

haccks
  • 104,019
  • 25
  • 176
  • 264
Hayri Uğur Koltuk
  • 2,970
  • 4
  • 31
  • 60
1

http://gcc.gnu.org/onlinedocs/cpp/Function-like-Macros.html#Function-like-Macros

Here you can see that calling the function, of which a macro with the same name exists, calls the macro instead :) For the gcc at least!

This would cause no problem, but quite some confusions. I wouldn't recommend this.

Theolodis
  • 4,977
  • 3
  • 34
  • 53
1

I will explain via cases:
If you declared the function first then the function like macro second, macro will over take the function. i.e. it will be called always instead of the function.

//Function
double squar(double x)
{
    return x*x;
}

//Macro
#define squar(x) (x*x)

On the other hand if you declare the macro first then the function later, an exception will be arise, you wont be able to build

//Macro
#define squar(x) (x*x)

//Function
double squar(double x)
{
    return x*x;
}

At the end, in the first case, you still call the function like @Hayri Uğur Koltuk said here in his answer by (squar)(5)

Community
  • 1
  • 1
Ahmed Hamdy
  • 2,547
  • 1
  • 17
  • 23