#define

I thought typedef was used for macros these days? Is #define used for this also?
sorry if this just seems like a dumb question - I'm reading a book that uses #define right out of the gate, so I am wondering if I was doing it wrong all a long when I was using typedef for this.

Thanks bob
Only #define can define macros. typedef does something entirely different, which is define an alias for a type. If typedef works for what you're trying to do then use it, as it's generally safer. The default policy for macros should be to avoid them if possible.
Sounds like the book you are reading ought to be considered suspect...
#define is a carryover from C. Coming from C, it's common to use defines for constants.
#define MAX_ROWS 1
C++ has constexpr for this.
constexpr int MAX_ROWS {1};

As helios mentioned, only #define can create macros and by extension, only #defines accept arguments. Another feature of #defines is token-pasting, Very useful if you need it, but generally something to be avoided.
Last edited on
only #defines accept argument
Well, not exactly. using can accept template arguments.
#define name
defines a token for the preprocessor, like include guards, which are important, or compiler flag things, eg do this block for windows, that block for unix in a build.

macros are not great. They are hard to debug, hard to read, and cause no end of aggravation if the () are wrong or something.
#define constants do not have a clean type. This can bite you sometimes in more type aware modern code.
typedef is fine but it is outdated due to using keyword. I honestly don't know that there is any real difference (?) there.
Last edited on
Thank you everyone, the book does speak of using them to create macros ( something I've never done). I kind a thought they were the same - - thanks for clarifying that for me.
I have no reason to use them ....
a few macros are critical for debugging. there are predefined tools like what file, and line number you are currently at in the code, good for error logs. And you are going to hit them on occasion in other people's code, esp if you run into some hybrid C / C++ projects. Just try to avoid creating one when it should have been a standard function. There is no sense in doing that and it causes nothing but problems.
Topic archived. No new replies allowed.