Thursday, May 2, 2013

Templates in C [Macros!]

Today I faced this problem of writing a generalized function in C that would accept a "configurable" type of argument. i.e. the function should be able to accept any kind of argument that I pass to it, and it should be able to do something with it (say print the value of the argument passed).

What I wanted could easily be done in C++ using TEMPLATES; create a function with a signature

void foo(class Template <T> x){
     cout << "x" << "\n";
     return ;
}

This cannot be done in C, as it is a middle level language (yes I said it! if you do not agree, go learn C++ STL :P ).

Now, there is NO (absolutely NO) way you can do function/operator overloading in C, hence we resort to finding workarounds... say what? macros biaatch!


MACROS - a coders nemesis -

Why:
1. Its difficult to write  a macro.
2. Its even more difficult to read a program with macros, you practically end up expanding the whole macros in your notebook / as comments in your code.
3. CSCOPE /CTAGS dont work on MACROS. you end up using grep instead to find out the exact place where the macro gets expanded.


Then Why do we still use it:
1. Makes ur code compact.
2. 1st reason is enough.

Without further ado, i present to you using macros to compactify (i just made that word up) your code.

consider the program :

int main(){
     callPrint_int(1);
     callPrint_float(4.2);
     callPrint_char('b');
     return 0;


1. Program without a macro:

callPrint_int(int x){
     cout << x;
}


callPrint_float(float x){
     cout << x;


callPrint_char(char x){
    cout << x;
}

2. Program with a macro: 

#define callPRINT(T) \
    void callPRINT_##T(T x) { cout << x ; }

callPRINT(int);
callPRINT(float);  
callPRINT(char);
  
each of the above three lines give you basically functions in part 1. but look at how compact your code becomes. isn't she a beauty :P.










  


3 comments:

  1. Ha ha .... loved it !! What application were you working on, that required C?? It has been a decade that I have used C.

    ReplyDelete
    Replies
    1. Hi Hrushikesh!

      I wrote some code to create a nfs-type filesystem in userspace. the src can be viewed here:: https://bitbucket.org/ShehbazJaffer/fuse-nfs/src

      Also, if you get time, read about FUSE. :)

      Delete
  2. This comment has been removed by the author.

    ReplyDelete