Pages

Friday, June 3, 2011

Definying variable names using macros

This is an interesting piece of information I came across while working on a project. Macros, provided by C, have always been something holding a lot of power. Today, I realized another powerful use of it.

Here is the piece of code that I came across (something similar)
#define SOME_FUNC(l,i) int l##_flag=i;
Now this note is made for future reference. Here the most intriguing (and confusing) was the use of the two hashes '#'. I just guessed that it helps use the 'name' of the variable. For example, if I call it as

SOME_FUNC(debug,3);
Using the rules of macro, this would change to
int debug_flag=3;

Now this is useful. A small test confirmed that this is exactly what was happening. Also, using the '--save-temps' attribute of 'gcc', I confirmed what I thought it was.

This could be very useful for debugging, as in the above example. Also, this could help us create a general function for creating flags to be created later. It is worthwhile to note that it cannot be used in an 'actual function' (that is not in the form of a macro). This is for the reason that when a function is called, the name of the variable is 'lost', and what remains is either the address or the value of the variable. Unlike function calls, macro expansion can allow the use of the name of the variable. The same could be used to make more complex functions (through the macro expansions).

NOTE: The above information is based on my own tests. I couldn't find any information on the net for the same and thought it was worthwhile making note of it.

2 comments:

  1. For the benefit of anyone seeking further information: http://en.wikipedia.org/wiki/C_preprocessor#Token_concatenation.

    ReplyDelete
  2. Stainless Steel Handle for Spinning Blades | Titsanium-Art
    Stainless Steel Handle for Spinning Blades. trekz titanium pairing We use stainless titanium pickaxe terraria steel, we have a wide selection hypoallergenic titanium earrings of blades. Spinning titanium wedding bands Blades $24.00 · keith titanium ‎In stock

    ReplyDelete