When to use typdef and define

Can someone list the thought process one goes through when deciding on wether to use typdef and define...pro's and con's of each

A snippet of code for examples would be fantastic :)
Last edited on
#define is more of a C way of doing things.

typedef or using is usually more appropriate.

Often used to shorten the name of complicated types, especially when some sort of template + container combination is used.
small ex: typedef Vector2<float> Vector2f;

Perhaps someone else can give a more detailed explanation.
You should always prefer typedef or using over #define. There are three main reasons that I can think of for this:
- #define replaces EVERYTHING. If you try to use a variable with that name it will be replaced, and weird things will start happening.
- #define isn't scoped. If you just want an alias for use within a function or class, a #define will ignore where you put it (though for a function, I guess you could follow it with a #undef).
- #defines aren't affected by their context, so you can't do things like create aliases for function pointers or template arguments.

Of course, sometimes a #define could be useful, but mostly in their form as macros.

The uses for typedef and using are not only for shortening the name of complicated types as @Ganado said, but are also used in templated code for relevant types that could change. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// A templated structure of some kind. 
template <typename T>
struct A {
    using type = T;

    void doSomething(T t) {
        // do something with t here
    }
};

// A function which has received an instance of something, possibly
// the above structure, but doesn't know which template and hence 
// what type to pass to its 'doSomething' member:
template <typename T>
void func(T& t) {
    T::type val;
    // calculate and do thing's with val in some way
    t.doSomething(val);
}

// ... possible use (in some function somewhere):
A<int> a;
func(a); // In func, 'val' will be of type 'int'. 
Last edited on
Topic archived. No new replies allowed.