What are macro in c and how they are defined
Printable View
What are macro in c and how they are defined
Macros are a preprocessor directive that replaces the macro name with the code in the definition before compilation.There's about a dozen and a half reasons not to use macros, but that's how they are defined if you wished to use them. Consider using inline functions instead.Code:#include <stdio>
#define myMacro printf("Hello World")
int main() {
myMacro;
return 0;
}
Hellow !!! this is a c forum not c++.Quote:
Originally Posted by SlyMaelstrom
You can inline functions in C, genius.
(Right?)
Yes, that's correct, my bad. Either way, avoid macros.
No, I don't believe it's standard. Some compilers will take it, but I think it just ignores the keyword when you compile a C source.Quote:
Originally Posted by ahluka
EDIT: Off of a little research it seems inlining was fully accepted into the C99 standard, so it may actually be applied in C code. I'm not positive, though.
Ok I didn't know that.
EDIT: You must be able to. I swear I've done it before. Unless I tricked myself into thinking I was using C. Hmm.
EDIT2: You have to stop editing at the same time as me.
c99 does support function inlining. Unfortunately, many people use microsoft compilers which do not handle c99.
Gcc does, though - just compile with -std=c99.
Code:#include <stdio.h>
#define SIX 1+5
#define NINE 8+1
int main ()
{
printf("%d times %d equals %d", SIX, NINE, SIX*NINE);
return 0;
}
> printf("%d times %d equals %d", SIX, NINE, SIX*NINE);
I wonder what this will print.
A demonstration of the precedence traps which can happen with macros no doubt :)