Typedefs and Define

What is the difference between typedef and #define ?

Typedef:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

typedef int hi;

int main(){
    hi a=1;
    cout<<a;
    return 0;
}


Define:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

using namespace std;

#define hi int

int main(){
    hi a=1;
    cout<<a;
    return 0;
}
Last edited on
A typedef is a type definition. When the compiler sees a typedef identifier, it will assume it's dealing with a data type.

#define is a pre-processor command, which replaces any instance of a defined identifier with a value, expression or another identifier. It's not just limited to data types.
Last edited on
line 5 #define hi int; Your code won't compile with that semi-colon...

a typedef is a way of creating an alias for a type. So in your code, whenever you use "hi", the compiler will treat it as a type that is identical to "int". So you get all the usual type checking and so on.

In general, you use typedef to create an easily managed alias for complicated declarations to save you a lot of typing, editing errors and sometimes it increases clarity.

A simple example:

typedef int (funp1)(int);

This introduces an alias "funp1" which is of type "pointer to function that takes one int parameter and returns int"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
typedef int (funp1)(int);

...

void func1(funp1 fun)
{
    int x =  funp1(x);
}
// the alternative here would be 
// void func1(int (funp1)(int))
...
int func(int y)
{
...
}
...
func1(func);


I don't think the preprocessor can help you much in this sort of situation, #define is used for text replacement. In your code, the preprocessor will replace every occurence of "hi" with "int". This is not the same thing, and can lead to a whole class of hard to find problems. The preprocessor has no concept of type, and does not respect namespaces.

In C, the preprocessor was used in this way to name constants and as a way of making small "functions" effecient. Both uses are deprecated in favour of actual compiler supported features in C++.

Take heed, the many hazards of using #define in this way have been widely documented.
Thanks
Topic archived. No new replies allowed.