16
#include<stdio.h>
void f(int a)
{
printf("%d", a);
}
#define f(a) {}

int main()
{
 /* call f : function */
}

How to call f (the function)? Writing f(3) doesn't work because it is replaced by {}

Ferdy
  • 341
  • 3
  • 6
  • 1
    Not stupid. Suppose you have a macro implementing an inline replacement for `f` in its header file, and you want to use this macro to define the external implementation in the implementation file. This is a standard practice. – R.. GitHub STOP HELPING ICE May 21 '11 at 12:30
  • It is stupid as an interview question. I wouldn't like to work for a company that needs this. – Bo Persson May 21 '11 at 13:09

4 Answers4

16

Does (f)(3); work?

The C preprocessor doesn't expand the macro f inside ( ).


Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
7
int main()
{
#undef f  // clear f!
 f(3);
}
iammilind
  • 68,093
  • 33
  • 169
  • 336
  • @Nyan, and you downvoted for that :). Questioner hasn't mentioned such condition. Take the case if the macro is defined in one common header file and being used in several other files. For the files you don't want to use that, you will simply `#undef` it. – iammilind May 21 '11 at 12:53
  • 4
    +1 for writing a correct answer that will probably annoy the interviewer! – Raynos May 21 '11 at 19:38
  • This is so destructive that it indeed seems fairly obvious that the OP wants to keep the macro unless otherwise stated, not the other way around. Otherwise, in his testcase, why begin with the macro defined at all? – Lightness Races in Orbit Oct 11 '12 at 12:36
4

Use function pointer to achieve this:

int main() {
    void (*p)(int a);
    p = f;
    p(3); //--> will call f(3)
    return 0;
}
pankiii
  • 435
  • 3
  • 9
1

One solution is posted by @Prasoon, another could be just introducing another name for the function, IF you can't change the function's name, neither the macro's name:

#include<stdio.h>
void f(int a)
{
   printf("%d", a);
}


#define fun (f) //braces is necessary 

#define f(a) {}

int main()
{
     fun(100);
}

Online demo : http://www.ideone.com/fbTcE

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • `How to call f` (aren't we calling `fun` here ? Because if calling `fun` was ok then we can change the name of the function `f()` to `fun()`. :) ) – iammilind May 21 '11 at 12:45
  • @iammilind: fun is not function, preprocessor replaces it with `f` (the actual function). – Nawaz May 21 '11 at 12:46