How do you write macros, and how do they work?
How do you write macros, and how do they work?
Like a normal function, sort of:
They have to be written in one single line, or use \ at the endof a line to break it into multiple lines.Code:#define PowerOfTwo(n) (n * n)
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.
Would it be possible to write most of a program using only pre-processing directives and marcos?
Macros directly modify your code, and hence, can be dangerous if not used properly. For example, let's take a look at a use of the macro provided above:
Now, clearly, the intended meaning is to assign z = (y + 1) * (y + 1) = 4 * 4 = 16. However, there is a direct substitution done, so what happens is: z = y + 1 * y + 1 = 2 * y + 1 = 7. This could be fixed as follows:Code:#define SQUARE(x) (x * x) int main( ) { int y = 3; int z = SQUARE(y + 1); }
... but it demonstrates the danger. As to writing a whole program using them... well, you have to have actual code in the macros themselves, and all you are going to do is make a mess, so unless you are writing code for say, the International Obfuscated C Code Contest, there is absolutely no point.Code:#define SQUARE(x) ((x) * (x))
The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.
Yes, but why would you want to?Originally Posted by Finchie_88
My best code is written with the delete key.
#define GREATER(x,y)(x>y?x:y)
Like that.
A note... If you do write macros, enclose all uses of your parameters in parentheses:
As I pointed out above, operator precedence can be a real pain dealing with macros, so make sure that you don't get any side effects.Code:#define GREATER(x,y)((x)>(y)?(x):(y))
The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.