Is a macro made to define constants? [duplicate]
Possible Duplicate:
"static const" vs "#define" in c
A macro is a fragment of code which has been given开发者_C百科 a name. Whenever the name is used, it is replaced by the contents of the macro. (No memory required)
So, people use it as a method to define constants instead of the syntax: const int num = 1;
Is this a good habit? Is the MACRO set to do another things additionally to #include
and #define
?
Macros can be used for other reasons than just defining constants. Nowadays, macro usage is generally frowned upon unless there are absolutely no other options available.
Debugging complex code with macros littered throughout can cause you more than one headache.
From GCC docs:
A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro.
Consts are generally preferred for several reasons. For example, they are a lenguage construct (not an external value processed by the preprocessor). Also, they contain type information, so they help the compiler to detect compiling errors, etc. In most cases, you could say they are equivalent, but const
is "semantically more correct".
精彩评论